Example #1
0
GeoIPXML::GeoIPXML( const QString& element )
    : GeoIP( element.isEmpty() ? QStringLiteral( "TimeZone" ) : element )
{
}
void PathChooser::slotBrowse()
{
    emit beforeBrowsing();

    QString predefined = path();
    if ((predefined.isEmpty() || !QFileInfo(predefined).isDir())
            && !d->m_initialBrowsePathOverride.isNull()) {
        predefined = d->m_initialBrowsePathOverride;
        if (!QFileInfo(predefined).isDir())
            predefined.clear();
    }

    // Prompt for a file/dir
    QString newPath;
    switch (d->m_acceptingKind) {
    case PathChooser::Directory:
    case PathChooser::ExistingDirectory:
        newPath = QFileDialog::getExistingDirectory(this,
                makeDialogTitle(tr("Choose Directory")), predefined);
        break;
    case PathChooser::ExistingCommand:
    case PathChooser::Command:
        newPath = QFileDialog::getOpenFileName(this,
                makeDialogTitle(tr("Choose Executable")), predefined,
                d->m_dialogFilter);
        break;
    case PathChooser::File: // fall through
        newPath = QFileDialog::getOpenFileName(this,
                makeDialogTitle(tr("Choose File")), predefined,
                d->m_dialogFilter);
        break;
    case PathChooser::SaveFile:
        newPath = QFileDialog::getSaveFileName(this,
                makeDialogTitle(tr("Choose File")), predefined,
                d->m_dialogFilter);
        break;
    case PathChooser::Any: {
        QFileDialog dialog(this);
        dialog.setFileMode(QFileDialog::AnyFile);
        dialog.setWindowTitle(makeDialogTitle(tr("Choose File")));
        QFileInfo fi(predefined);
        if (fi.exists())
            dialog.setDirectory(fi.absolutePath());
        // FIXME: fix QFileDialog so that it filters properly: lib*.a
        dialog.setNameFilter(d->m_dialogFilter);
        if (dialog.exec() == QDialog::Accepted) {
            // probably loop here until the *.framework dir match
            QStringList paths = dialog.selectedFiles();
            if (!paths.isEmpty())
                newPath = paths.at(0);
        }
        break;
        }

    default:
        break;
    }

    // Delete trailing slashes unless it is "/"|"\\", only
    if (!newPath.isEmpty()) {
        newPath = QDir::toNativeSeparators(newPath);
        if (newPath.size() > 1 && newPath.endsWith(QDir::separator()))
            newPath.truncate(newPath.size() - 1);
        setPath(newPath);
    }

    emit browsingFinished();
    d->m_lineEdit->triggerChanged();
}
Example #3
0
void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks)
{
    // don't show / hide progressBar and it's label if we have no connection(s) to the network
    if (!clientModel || clientModel->getNumConnections() == 0)
    {
        progressBarLabel->setVisible(false);
        progressBar->setVisible(false);

        return;
    }

    QString tooltip;

    if(count < nTotalBlocks)
    {
        int nRemainingBlocks = nTotalBlocks - count;
        float nPercentageDone = count / (nTotalBlocks * 0.01f);

        if (clientModel->getStatusBarWarnings() == "")
        {
            progressBarLabel->setText(tr("Synchronizing with network..."));
            progressBarLabel->setVisible(true);
            progressBar->setFormat(tr("~%n block(s) remaining", "", nRemainingBlocks));
            progressBar->setMaximum(nTotalBlocks);
            progressBar->setValue(count);
            progressBar->setVisible(true);
        }
        else
        {
            progressBarLabel->setText(clientModel->getStatusBarWarnings());
            progressBarLabel->setVisible(true);
            progressBar->setVisible(false);
        }
        tooltip = tr("Downloaded %1 of %2 blocks of transaction history (%3% done).").arg(count).arg(nTotalBlocks).arg(nPercentageDone, 0, 'f', 2);
    }
    else
    {
        if (clientModel->getStatusBarWarnings() == "")
            progressBarLabel->setVisible(false);
        else
        {
            progressBarLabel->setText(clientModel->getStatusBarWarnings());
            progressBarLabel->setVisible(true);
        }
        progressBar->setVisible(false);
        tooltip = tr("Downloaded %1 blocks of transaction history.").arg(count);
    }

    tooltip = tr("Current difficulty is %1.").arg(clientModel->GetDifficulty()) + QString("<br>") + tooltip;

    QDateTime now = QDateTime::currentDateTime();
    QDateTime lastBlockDate = clientModel->getLastBlockDate();
    int secs = lastBlockDate.secsTo(now);
    QString text;

    // Represent time from last generated block in human readable text
    if(secs <= 0)
    {
        // Fully up to date. Leave text empty.
    }
    else if(secs < 60)
    {
        text = tr("%n second(s) ago","",secs);
    }
    else if(secs < 60*60)
    {
        text = tr("%n minute(s) ago","",secs/60);
    }
    else if(secs < 24*60*60)
    {
        text = tr("%n hour(s) ago","",secs/(60*60));
    }
    else
    {
        text = tr("%n day(s) ago","",secs/(60*60*24));
    }

    // Set icon state: spinning if catching up, tick otherwise
    if(secs < 90*60 && count >= nTotalBlocks)
    {
        tooltip = tr("Up to date") + QString(".<br>") + tooltip;
        labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));

        overviewPage->showOutOfSyncWarning(false);
    }
    else
    {
        tooltip = tr("Catching up...") + QString("<br>") + tooltip;
        labelBlocksIcon->setMovie(syncIconMovie);
        syncIconMovie->start();

        overviewPage->showOutOfSyncWarning(true);
    }

    if(!text.isEmpty())
    {
        tooltip += QString("<br>");
        tooltip += tr("Last received block was generated %1.").arg(text);
    }

    // Don't word-wrap this (fixed-width) tooltip
    tooltip = QString("<nobr>") + tooltip + QString("</nobr>");

    labelBlocksIcon->setToolTip(tooltip);
    progressBarLabel->setToolTip(tooltip);
    progressBar->setToolTip(tooltip);
}
Example #4
0
QgsRasterLayer* QgsRemoteOWSBuilder::wcsLayerFromUrl( const QString &url,
    const QString &layerName,
    QList<QTemporaryFile*> &filesToRemove,
    QList<QgsMapLayer*> &layersToRemove,
    bool allowCaching ) const
{
  Q_UNUSED( layerName );
  Q_UNUSED( allowCaching );
  QgsDebugMsg( "Entering" );

  //write server url and coverage name to a temporary file
  QString fileName = createTempFile();
  if ( fileName.isEmpty() )
  {
    return 0;
  }

  QFile tempFile( fileName );

  QTemporaryFile* tmpFile = new QTemporaryFile();
  if ( !tmpFile->open() )
  {
    delete tmpFile;
    return 0;
  }

  filesToRemove.push_back( tmpFile ); //make sure the temporary file gets deleted after each request

  QgsDebugMsg( "opening successful" );
  QgsDebugMsg( "url: " + url );
  //extract server url and coverage name from string
  QStringList serverSplit = url.split( "?" );
  if ( serverSplit.size() < 2 )
  {
    QgsDebugMsg( "error, no '?' contained in url" );
    return 0;
  }
  QString serverUrl = serverSplit.at( 0 );
  QString request = serverSplit.at( 1 );
  QStringList parameterSplit = request.split( "&" );
  QString coverageName;
  QString format;
  for ( int i = 0; i < parameterSplit.size(); ++i )
  {
    if ( parameterSplit.at( i ).startsWith( "COVERAGE", Qt::CaseInsensitive ) )
    {
      coverageName = parameterSplit.at( i ).split( "=" ).at( 1 );
    }
    else if ( parameterSplit.at( i ).startsWith( "FORMAT", Qt::CaseInsensitive ) )
    {
      format = parameterSplit.at( i ).split( "=" ).at( 1 );
    }
  }

  if ( coverageName.isEmpty() )
  {
    QgsDebugMsg( "coverage name is empty" );
    return 0;
  }

  if ( format.isEmpty() )
  {
    format = "GeoTIFF"; //use geotiff as default
  }

  QgsDebugMsg( "wcs server url: " + serverUrl );
  QgsDebugMsg( "coverage name: " + coverageName );

  //fetch WCS layer in the current resolution as geotiff
  QString wcsRequest = serverUrl + "?SERVICE=WCS&VERSION=1.0.0&REQUEST=GetCoverage&COVERAGE=" + coverageName + "&FORMAT=" + format;

  //CRS (or SRS)
  QString crs = mParameterMap.value( "CRS", mParameterMap.value( "SRS" ) );
  if ( crs.isEmpty() )
  {
    QgsDebugMsg( "No CRS or SRS parameter found for wcs layer, returning 0" );
    return 0;
  }
  wcsRequest += "&CRS=" + crs;

  //width
  QString width = mParameterMap.value( "WIDTH" );
  if ( width.isEmpty() )
  {
    QgsDebugMsg( "No WIDTH parameter found for wcs layer, returning 0" );
    return 0;
  }
  wcsRequest += "&WIDTH=" + width;

  //height
  QString height = mParameterMap.value( "HEIGHT" );
  if ( height.isEmpty() )
  {
    QgsDebugMsg( "No HEIGHT parameter found for wcs layer, returning 0" );
    return 0;
  }
  wcsRequest += "&HEIGHT=" + height;

  //bbox
  QString bbox = mParameterMap.value( "BBOX" );
  if ( bbox.isEmpty() )
  {
    QgsDebugMsg( "No BBOX parameter found for wcs layer, returning 0" );
    return 0;
  }
  wcsRequest += "&BBOX=" + bbox;

  QgsDebugMsg( "WCS request is: " + wcsRequest );

  //make request and store byte array into temporary file
  QgsHttpTransaction httpTransaction( wcsRequest );
  QByteArray result;
  if ( !httpTransaction.getSynchronously( result ) )
  {
    return 0;
  }

  QDataStream tempFileStream( &tempFile );
  tempFileStream.writeRawData( result.data(), result.size() );
  tempFile.close();

  QgsRasterLayer* rl = new QgsRasterLayer( fileName, layerNameFromUri( fileName ) );
  layersToRemove.push_back( rl ); //make sure the layer gets deleted after each request
  return rl;
}
Example #5
0
void MozQWidget::inputMethodEvent(QInputMethodEvent* aEvent)
{
    QString currentPreeditString = aEvent->preeditString();
    QString currentCommitString = aEvent->commitString();

    //first check for some controllkeys send as text...
    if (currentCommitString == " ") {
        sendPressReleaseKeyEvent(Qt::Key_Space, currentCommitString.unicode());
    } else if (currentCommitString == "\n") {
        sendPressReleaseKeyEvent(Qt::Key_Return, currentCommitString.unicode());
    } else if (currentCommitString.isEmpty()) {
        //if its no controllkey than check if current Commit is empty
        //if yes than we have some preedit text here
        if (currentPreeditString.length() == 1 && gLastPreeditString.isEmpty()) {
            //Preedit text can change its entire look'a'like
            //check if length of new compared to the old is 1,
            //means that its a new startup
            sendPressReleaseKeyEvent(0, currentPreeditString.unicode());
        } else if (currentPreeditString.startsWith(gLastPreeditString)) {
            //Length was not 1 or not a new startup
            //check if the current preedit starts with the last one,
            //if so: Add new letters (note: this can be more then one new letter)
            const QChar * text = currentPreeditString.unicode();
            for (int i = gLastPreeditString.length(); i < currentPreeditString.length(); i++) {
                sendPressReleaseKeyEvent(0, &text[i]);
            }
        } else {
            //last possible case, we had a PreeditString which was now completely changed.
            //first, check if just one letter was removed (normal Backspace case!)
            //if so: just send the backspace
            QString tempLastPre = gLastPreeditString;
            tempLastPre.truncate(gLastPreeditString.length()-1);
            if (currentPreeditString == tempLastPre) {
                sendPressReleaseKeyEvent(Qt::Key_Backspace);
            } else if (currentPreeditString != tempLastPre) {
                //more than one character changed, so just renew everything
                //delete all preedit
                for (int i = 0; i < gLastPreeditString.length(); i++) {
                    sendPressReleaseKeyEvent(Qt::Key_Backspace);
                }
                //send new Preedit
                const QChar * text = currentPreeditString.unicode();
                for (int i = 0; i < currentPreeditString.length(); i++) {
                    sendPressReleaseKeyEvent(0, &text[i]);
                }
            }
        }
    } else if (gLastPreeditString != currentCommitString) {
        //User commited something
        if (currentCommitString.length() == 1 && gLastPreeditString.isEmpty()) {
            //if commit string ist one and there is no Preedit String
            //case i.e. when no error correction is enabled in the system (default meego.com)
            sendPressReleaseKeyEvent(0, currentCommitString.unicode());
        } else {
            //There is a Preedit, first remove it
            for (int i = 0; i < gLastPreeditString.length(); i++) {
                sendPressReleaseKeyEvent(Qt::Key_Backspace);
            }
            //Now push commited String into
            const QChar * text = currentCommitString.unicode();
            for (int i = 0; i < currentCommitString.length(); i++) {
                sendPressReleaseKeyEvent(0, &text[i]);
            }
        }
    }

    //save preedit for next round.
    gLastPreeditString = currentPreeditString;

    //pre edit is continues string of new chars pressed by the user.
    //if pre edit is changing rapidly without commit string first then user choose some overed text
    //if commitstring comes directly after, forget about it
    QGraphicsWidget::inputMethodEvent(aEvent);
}
static bool parse_chan_info(const QString   &rawdata,
                            IPTVChannelInfo &info,
                            QString         &channum,
                            uint            &lineNum)
{
    // #EXTINF:0,2 - France 2                <-- duration,channum - channame
    // #EXTMYTHTV:xmltvid=C2.telepoche.com   <-- optional line (myth specific)
    // #EXTMYTHTV:bitrate=BITRATE            <-- optional line (myth specific)
    // #EXTMYTHTV:fectype=FECTYPE            <-- optional line (myth specific)
    //     The FECTYPE can be rfc2733, rfc5109, or smpte2022
    // #EXTMYTHTV:fecurl0=URL                <-- optional line (myth specific)
    // #EXTMYTHTV:fecurl1=URL                <-- optional line (myth specific)
    // #EXTMYTHTV:fecbitrate0=BITRATE        <-- optional line (myth specific)
    // #EXTMYTHTV:fecbitrate1=BITRATE        <-- optional line (myth specific)
    // #...                                  <-- ignored comments
    // rtsp://maiptv.iptv.fr/iptvtv/201 <-- url

    QString name;
    QMap<QString,QString> values;

    while (true)
    {
        QString line = rawdata.section("\n", lineNum, lineNum);
        if (line.isEmpty())
            return false;

        ++lineNum;
        if (line.startsWith("#"))
        {
            if (line.startsWith("#EXTINF:"))
            {
                parse_extinf(line.mid(line.indexOf(':')+1), channum, name);
            }
            else if (line.startsWith("#EXTMYTHTV:"))
            {
                QString data = line.mid(line.indexOf(':'));
                QString key = data.left(data.indexOf('='));
                if (!key.isEmpty())
                    values[key] = data.mid(data.indexOf('=')+1);
            }
            continue;
        }

        if (name.isEmpty())
            return false;

        QMap<QString,QString>::const_iterator it = values.begin();
        for (; it != values.end(); ++it)
        {
            LOG(VB_GENERAL, LOG_INFO,
                QString("parse_chan_info [%1]='%2'")
                .arg(it.key()).arg(*it));
        }
        info = IPTVChannelInfo(
            name, values["xmltvid"],
            line, values["bitrate"].toUInt(),
            values["fectype"],
            values["fecurl0"], values["fecbitrate0"].toUInt(),
            values["fecurl1"], values["fecbitrate1"].toUInt());
        return true;
    }
}
Example #7
0
void ShortcutConfig::textFileClicked()
{
  textFileButton->setDown(false);

  QString fname = QFileDialog::getSaveFileName(this,
                                               tr("Save printable text file"),
                                               QDir::homePath() + "/shortcuts.txt",
                                               tr("Text files (*.txt);;All files (*)"));
  if(fname.isEmpty())
  {
    //QMessageBox::critical(this, tr("Error"), tr("Selected file name is empty"));
    return;
  }
  
  QFile qf(fname);
  if(!qf.open(QIODevice::WriteOnly | QIODevice::Text))
  {
    QMessageBox::critical(this, tr("Error"), tr("Error opening file for saving"));
    return;
  }

  bool error = false;

  QString header;
  for (int i=0; i < SHRT_NUM_OF_CATEGORIES; i++)
  {
    if(shortcut_category[i].id_flag == current_category)
    {
      header = QString(PACKAGE_NAME) + " " + tr("Shortcuts for selected category: ") + QString(shortcut_category[i].name) + "\n\n";
      break;
    }
  }
  if(!header.isEmpty() && qf.write(header.toLatin1().constData()) == -1)
    error = true;

  QString info;
  if(current_category == ALL_SHRT)
  {
    info = tr("Legend:\n");
    for (int i=0; i < SHRT_NUM_OF_CATEGORIES; i++)
    {
      if(shortcut_category[i].id_flag == ALL_SHRT)
        continue;
      info += (QString::number(i) + " : " + QString(shortcut_category[i].name) + "\n");
    }
    info += "\n";
  }
  if(!info.isEmpty() && qf.write(info.toLatin1().constData()) == -1)
    error = true;
  
  for(int i=0; i < SHRT_NUM_OF_ELEMENTS; i++)
  {
    if(shortcuts[i].type & current_category)
    {
          QString s;
          int pos = 0;
          if(current_category == ALL_SHRT)
          {
            for(int j=0; j < SHRT_NUM_OF_CATEGORIES; j++)
            {
              if(shortcut_category[j].id_flag == ALL_SHRT)
                continue;
              if(shortcuts[i].type & shortcut_category[j].id_flag)
                s.insert(pos, QString::number(j));
              pos += 3;
            }
            s.insert(pos, " : ");
            pos += 3;
          }

          s.insert(pos, QKeySequence(shortcuts[i].key).toString());
          pos += 25;
          s.insert(pos, qApp->translate("shortcuts", shortcuts[i].descr) + "\n");
          if(qf.write(s.toLatin1().constData()) == -1)
            error = true;
    }
  }
  
  qf.close();

  if(error)
    QMessageBox::critical(this, tr("Error"), tr("An error occurred while saving"));
}
Example #8
0
void QgsColorDialogV2::setTitle( const QString title )
{
  setWindowTitle( title.isEmpty() ? tr( "Select Color" ) : title );
}
ERR cmdDeleteFromServer::exec()
{
  OnlineMngr* om = db->getOnlineManager();

  // if the user hasn't registered yet,
  // it's pointless to proceed.
  // This should be checked by the caller
  // (e.g., by menu locking/disabling), so
  // we quit without error message
  if (!(om->hasRegistrationSubmitted()))
  {
    return ERR::WRONG_STATE;  // dummy value
  }

  // ask for confirmation
  QString msg = tr("<p>Do you really want to delete the tournament from the server?</p>");
  msg += tr("<p>The deletion <b>cannot be undone</b> and is effective immediately.</p>");
  int rc = QMessageBox::question(parentWidget, tr("Delete tournament from server"), msg);
  if (rc != QMessageBox::Yes) return ERR::OK;

  // check whether the server is online and whether we
  // have a network connection
  //
  // this can last up to five seconds (--> timeout) and thus
  // we better enable the hourglass cursor
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  int tripTime = om->ping();
  QApplication::restoreOverrideCursor();

  // if tripTime is less than zero, an error occurred
  if (tripTime < 0)
  {
    QString msg = tr("The tournament server is currently not available or there is no working internet connection.\n\nPlease try again later.");
    QMessageBox::information(parentWidget, tr("Remove tournament from server"), msg);
    return ERR::WRONG_STATE;  // dummy error code; will not be evaluated by caller
  }

  // if the secret signing key has not yet been unlocked, ask the
  // user for the password and unlock the keystore
  if (!(om->isUnlocked()))
  {
    cmdUnlockKeystore cmd{parentWidget, db};
    ERR err = cmd.exec();
    if (err != ERR::OK) return err;
  }

  QString errTxt;
  OnlineError err = om->deleteFromServer(errTxt);

  // handle connection / transport errors
  if ((err != OnlineError::Okay) && (err != OnlineError::TransportOkay_AppError))
  {
    QString msg;
    switch (err)
    {
    case OnlineError::Timeout:
      msg = tr("The server is currently not available.\n\n");
      msg += tr("Maybe the server is temporarily down or you are offline.");
      break;

    case OnlineError::BadRequest:
      msg = tr("The server did not accept our connection request (400, BadRequest).");
      break;

    case OnlineError::IncompatibleVersions:
      msg = tr("<p>This version of QTournament is incompatible with the server.</p>");
      msg += tr("<p>Please download a more recent version from:</p>");
      msg += "<p><a href='http://qtournament.de'>QTournament.de</a></p>";
      break;

    case OnlineError::LocalDatabaseError:
      msg = tr("<p>A local database error has occurred.</p>");
      msg += tr("<p>The tournament has been deleted on the server but the local database file is now inconsistent.</p>");
      msg += tr("<p>You can safely continue with the tournament but online functions will not work as expected anymore.</p>");
      break;

    default:
      msg = tr("Deletion failed due to an unspecified network or server error!");
    }

    QMessageBox::warning(parentWidget, tr("Connection failed"), msg);
    return ERR::WRONG_STATE; // dummy value
  }

  // at this point, the data exchange with the server was successful (HTTP and Signatures).
  // We only have to check if the request on application level was successful as well.

  if (err == OnlineError::Okay)
  {
    QMessageBox::information(parentWidget, tr("Deletion successful"), tr("The tournament has been successfully deleted from the server!"));

    return ERR::OK;
  }

  if (errTxt == "DatabaseError")
  {
    msg = tr("You cannot connect because of a server-side database error.\n");
    msg += tr("Please try again later!");
  }
  if (msg.isEmpty())
  {
    msg = tr("You cannot delete the tournament because of an unexpected server error.\n");
    msg += tr("Please try again later!");
  }

  QMessageBox::warning(parentWidget, tr("Connection failed"), msg);
  return ERR::WRONG_STATE; // dummy value

}
Example #10
0
QString GitSubmitEditor::amendSHA1() const
{
    QString commit = submitEditorWidget()->amendSHA1();
    return commit.isEmpty() ? m_amendSHA1 : commit;
}
/// When something is changed here, also change ReadingContext::lookupProperty in
/// texttomodelmerger.cpp
/// ### Maybe put this into the context as a helper method.
const Value *Check::checkScopeObjectMember(const UiQualifiedId *id)
{
    QList<const ObjectValue *> scopeObjects = _context.scopeChain().qmlScopeObjects;
    if (scopeObjects.isEmpty())
        return 0;

    if (! id)
        return 0; // ### error?

    if (! id->name) // possible after error recovery
        return 0;

    QString propertyName = id->name->asString();

    if (propertyName == QLatin1String("id") && ! id->next)
        return 0; // ### should probably be a special value

    // attached properties
    bool isAttachedProperty = false;
    if (! propertyName.isEmpty() && propertyName[0].isUpper()) {
        isAttachedProperty = true;
        scopeObjects += _context.scopeChain().qmlTypes;
    }

    if (scopeObjects.isEmpty())
        return 0;

    // global lookup for first part of id
    const Value *value = 0;
    for (int i = scopeObjects.size() - 1; i >= 0; --i) {
        value = scopeObjects[i]->lookupMember(propertyName, &_context);
        if (value)
            break;
    }
    if (!value) {
        error(id->identifierToken,
              Check::tr("'%1' is not a valid property name").arg(propertyName));
    }

    // can't look up members for attached properties
    if (isAttachedProperty)
        return 0;

    // member lookup
    const UiQualifiedId *idPart = id;
    while (idPart->next) {
        const ObjectValue *objectValue = value_cast<const ObjectValue *>(value);
        if (! objectValue) {
            error(idPart->identifierToken,
                  Check::tr("'%1' does not have members").arg(propertyName));
            return 0;
        }

        if (! idPart->next->name) {
            // somebody typed "id." and error recovery still gave us a valid tree,
            // so just bail out here.
            return 0;
        }

        idPart = idPart->next;
        propertyName = idPart->name->asString();

        value = objectValue->lookupMember(propertyName, &_context);
        if (! value) {
            error(idPart->identifierToken,
                  Check::tr("'%1' is not a member of '%2'").arg(
                          propertyName, objectValue->className()));
            return 0;
        }
    }

    return value;
}
Example #12
0
bool AACDecoder::decode(const QString &sourceFile, const QString &outputFile, volatile bool *abortFlag)
{
	QProcess process;
	QStringList args;

	args << "-o" << QDir::toNativeSeparators(outputFile);
	args << QDir::toNativeSeparators(sourceFile);

	if(!startProcess(process, m_binary, args))
	{
		return false;
	}

	bool bTimeout = false;
	bool bAborted = false;

	QRegExp regExp("\\[(\\d+)%\\]\\s+decoding\\s+");

	while(process.state() != QProcess::NotRunning)
	{
		if(*abortFlag)
		{
			process.kill();
			bAborted = true;
			emit messageLogged("\nABORTED BY USER !!!");
			break;
		}
		process.waitForReadyRead(m_processTimeoutInterval);
		if(!process.bytesAvailable() && process.state() == QProcess::Running)
		{
			process.kill();
			qWarning("FAAD process timed out <-- killing!");
			emit messageLogged("\nPROCESS TIMEOUT !!!");
			bTimeout = true;
			break;
		}
		while(process.bytesAvailable() > 0)
		{
			QByteArray line = process.readLine();
			QString text = QString::fromUtf8(line.constData()).simplified();
			if(regExp.lastIndexIn(text) >= 0)
			{
				bool ok = false;
				int progress = regExp.cap(1).toInt(&ok);
				if(ok) emit statusUpdated(progress);
			}
			else if(!text.isEmpty())
			{
				emit messageLogged(text);
			}
		}
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}
	
	emit statusUpdated(100);
	emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

	if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS || QFileInfo(outputFile).size() == 0)
	{
		return false;
	}
	
	return true;
}
Example #13
0
bool AACDecoder::isFormatSupported(const QString &containerType, const QString &containerProfile, const QString &formatType, const QString &formatProfile, const QString &formatVersion)
{
	if(containerType.compare("ADTS", Qt::CaseInsensitive) == 0 || containerType.compare("MPEG-4", Qt::CaseInsensitive) == 0)
	{
		if(formatType.compare("AAC", Qt::CaseInsensitive) == 0)
		{
			QStringList profileParts = formatProfile.split(" ", QString::SkipEmptyParts);
			if(profileParts.contains("LC", Qt::CaseInsensitive) || profileParts.contains("HE-AAC", Qt::CaseInsensitive) || profileParts.contains("HE-AACv2", Qt::CaseInsensitive))
			{
				if(formatVersion.compare("Version 2", Qt::CaseInsensitive) == 0 || formatVersion.compare("Version 4", Qt::CaseInsensitive) == 0 || formatVersion.isEmpty())
				{
					return true;
				}
			}
		}
	}

	return false;
}
void QmitkRigidRegistrationSelectorView::DoSaveRigidRegistrationParameter()
{
  bool ok;
  QString text = QInputDialog::getText(this,
    "Save Parameter Preset", "Enter name for preset:", QLineEdit::Normal,
    QString::null, &ok );
  if ( ok )
  {
    std::map<std::string, itk::Array<double> > existingPresets;
    existingPresets = m_Preset->getTransformValuesPresets();

    auto iter = existingPresets.find(std::string((const char*)text.toLatin1()));
    if (iter != existingPresets.end())
    {
      QMessageBox::critical( this, "Preset definition",
        "Presetname already exists.");
      return;
    }
    if (text.isEmpty())
    {
      QMessageBox::critical( this, "Preset definition",
        "Presetname has to be set.\n"
        "You have to enter a Presetname." );
      return;
    }
    itk::Array<double> transformValues;
    transformValues.SetSize(25);
    transformValues.fill(0);
    transformValues[0] = m_Controls.m_TransformBox->currentIndex();

    itk::Array<double> transformValuesFromGUI = dynamic_cast<QmitkRigidRegistrationTransformsGUIBase*>(m_Controls.m_TransformWidgetStack->currentWidget())->GetTransformParameters();
    for (unsigned int i = 0; i < transformValuesFromGUI.Size(); i++)
    {
      transformValues[i+1] = transformValuesFromGUI[i];
    }

    std::map<std::string, itk::Array<double> > transformMap;
    transformMap = m_Preset->getTransformValuesPresets();

    transformMap[std::string((const char*)text.toLatin1())] = transformValues;

    itk::Array<double> metricValues;
    metricValues.SetSize(25);
    metricValues.fill(0);
    metricValues[0] = m_Controls.m_MetricBox->currentIndex();
    itk::Array<double> metricValuesFromGUI = dynamic_cast<QmitkRigidRegistrationMetricsGUIBase*>(m_Controls.m_MetricWidgetStack->currentWidget())->GetMetricParameters();
    for (unsigned int i = 0; i < metricValuesFromGUI.Size(); i++)
    {
      metricValues[i+1] = metricValuesFromGUI[i];
    }

    std::map<std::string, itk::Array<double> > metricMap;
    metricMap = m_Preset->getMetricValuesPresets();

    metricMap[std::string((const char*)text.toLatin1())] = metricValues;

    itk::Array<double> optimizerValues;
    optimizerValues.SetSize(25);
    optimizerValues.fill(0);
    optimizerValues[0] = m_Controls.m_OptimizerBox->currentIndex();
    itk::Array<double> optimizerValuesFromGUI = dynamic_cast<QmitkRigidRegistrationOptimizerGUIBase*>(m_Controls.m_OptimizerWidgetStack->currentWidget())->GetOptimizerParameters();
    for (unsigned int i = 0; i < optimizerValuesFromGUI.Size(); i++)
    {
      optimizerValues[i+1] = optimizerValuesFromGUI[i];
    }

    std::map<std::string, itk::Array<double> > optimizerMap;
    optimizerMap = m_Preset->getOptimizerValuesPresets();

    optimizerMap[std::string((const char*)text.toLatin1())] = optimizerValues;

    itk::Array<double> interpolatorValues;
    interpolatorValues.SetSize(25);
    interpolatorValues.fill(0);
    interpolatorValues[0] = m_Controls.m_InterpolatorBox->currentIndex();

    std::map<std::string, itk::Array<double> > interpolatorMap;
    interpolatorMap = m_Preset->getInterpolatorValuesPresets();

    interpolatorMap[std::string((const char*)text.toLatin1())] = interpolatorValues;

    m_Preset->newPresets(transformMap, metricMap, optimizerMap, interpolatorMap);

  }
  else
  {
    // user pressed Cancel
  }
}
Example #15
0
int main(int argc, char **argv)
{
	KAboutData about("kdedtester", I18N_NOOP("KDED Module tester"), version, description,
		     KAboutData::License_GPL, "(C) 2004 Diego 'Flameeyes' Pettenò", 0, 0, "*****@*****.**");
	about.addAuthor( "Diego 'Flameeyes' Pettenò", 0, "*****@*****.**" );
	KCmdLineArgs::init(argc, argv, &about);
	KCmdLineArgs::addCmdLineOptions( options );
	KApplication app;

	// no session.. just start up normally
	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
	
	if ( args->count() == 0 )
	{
		kdError() << "You must call kdedtester with a valid kded module name." << endl;
		return -1;
	}

	/// @todo do something with the command line args here
	QCString modulename = args->arg(0);
	args->clear();
	
	if ( modulename.isEmpty() )
	{
		kdError() << "You must call kdedtester with a valid kded module name." << endl;
		return -1;
	}
	
	KService::Ptr s = KService::serviceByDesktopPath("kded/"+modulename+".desktop");
	if ( ! s || s->library().isEmpty() )
	{
		kdError() << "Unable to load the service for requested module." << endl;
		return -2;
	}
	
	// get the library loader instance
	KLibLoader *loader = KLibLoader::self();
	
	QVariant v = s->property("X-KDE-Factory");
	QString factory = v.isValid() ? v.toString() : QString::null;
	if (factory.isEmpty())
		factory = s->library();

	factory = "create_" + factory;
	QString libname = "kded_"+s->library();
	
	kdWarning() << "Recap: the factory is '" << factory << "', and the library '" << libname << "'." << endl;

	KLibrary *lib = loader->library(QFile::encodeName(libname));
	if ( ! lib )
	{
		kdWarning() << "Library not found, trying '" << libname << "' instead" << endl
			<< "KLibLoader says: " << loader->lastErrorMessage() << endl;
		
		libname.prepend("lib");
		lib = loader->library(QFile::encodeName(libname));
	}
	
	if ( ! lib )
	{
		kdError() << "Library still not found. Exiting." << endl
			<< "KLibLoader says: " << loader->lastErrorMessage() << endl;
		return -3;
	}
	
	void *create = lib->symbol(QFile::encodeName(factory));
	if ( ! create )
	{
		kdError() << "Unable to find factory symbol into library. Exiting." << endl;
		loader->unloadLibrary(QFile::encodeName(libname));
		return -4;
	}
	
        KDEDModule* (*func)(const QCString &);
        func = (KDEDModule* (*)(const QCString &)) create;
	
	KDEDModule *module = func(modulename);
	if ( ! module )
	{
		kdError() << "Factory returned NULL module. Exiting." << endl;
		loader->unloadLibrary(QFile::encodeName(libname));
		return -5;
	}
	
	delete module;
	loader->unloadLibrary(QFile::encodeName(libname));
	kdWarning() << "Module loaded (and already unloaded) correctly." << endl;
	return 0;
}
Example #16
0
void MoreInfo::urlChanged(const QString &text)
{
    btnHomePage->setEnabled(!text.isEmpty());
}
fbox_chan_map_t IPTVChannelFetcher::ParsePlaylist(
    const QString &reallyrawdata, IPTVChannelFetcher *fetcher)
{
    fbox_chan_map_t chanmap;

    QString rawdata = reallyrawdata;
    rawdata.replace("\r\n", "\n");

    // Verify header is ok
    QString header = rawdata.section("\n", 0, 0);
    if (header != "#EXTM3U")
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("Invalid channel list header (%1)").arg(header));

        if (fetcher)
        {
            fetcher->SetMessage(
                QObject::tr("ERROR: M3U channel list is malformed"));
        }

        return chanmap;
    }

    // estimate number of channels
    if (fetcher)
    {
        uint num_channels = estimate_number_of_channels(rawdata);
        fetcher->SetTotalNumChannels(num_channels);

        LOG(VB_CHANNEL, LOG_INFO,
            QString("Estimating there are %1 channels in playlist")
                .arg(num_channels));
    }

    // Parse each channel
    uint lineNum = 1;
    for (uint i = 1; true; i++)
    {
        IPTVChannelInfo info;
        QString channum = QString::null;

        if (!parse_chan_info(rawdata, info, channum, lineNum))
            break;

        QString msg = QObject::tr("Encountered malformed channel");
        if (!channum.isEmpty())
        {
            chanmap[channum] = info;

            msg = QObject::tr("Parsing Channel #%1 : %2 : %3")
                .arg(channum).arg(info.m_name)
                .arg(info.m_tuning.GetDataURL().toString());
            LOG(VB_CHANNEL, LOG_INFO, msg);

            msg = QString::null; // don't tell fetcher
        }

        if (fetcher)
        {
            if (!msg.isEmpty())
                fetcher->SetMessage(msg);
            fetcher->SetNumChannelsParsed(i);
        }
    }

    return chanmap;
}
Example #18
0
/** @brief Parse xml-data
 *----------------------------------------------------------------------------*/
void ParseObject::slotParse(const QByteArray &xmlData, const int &feedId,
                            const QDateTime &dtReply, const QString &codecName)
{
  if (mainApp->isSaveDataLastFeed()) {
    QFile file(mainApp->dataDir()  + "/lastfeed.dat");
    file.open(QIODevice::WriteOnly);
    file.write(xmlData);
    file.close();
  }

  qDebug() << "=================== parseXml:start ============================";

  db_.transaction();

  // extract feed id and duplicate news mode from feed table
  parseFeedId_ = feedId;
  QString feedUrl;
  duplicateNewsMode_ = false;
  QSqlQuery q(db_);
  q.setForwardOnly(true);
  q.exec(QString("SELECT duplicateNewsMode, xmlUrl FROM feeds WHERE id=='%1'").arg(parseFeedId_));
  if (q.first()) {
    duplicateNewsMode_ = q.value(0).toBool();
    feedUrl = q.value(1).toString();
  }

  // id not found (ex. feed deleted while updating)
  if (feedUrl.isEmpty()) {
    qWarning() << QString("Feed with id = '%1' not found").arg(parseFeedId_);
    emit signalFinishUpdate(parseFeedId_, false, 0, "0");
    db_.commit();
    return;
  }

  qDebug() << QString("Feed '%1' found with id = %2").arg(feedUrl).arg(parseFeedId_);

  // actually parsing
  feedChanged_ = false;

  bool codecOk = false;
  QString convertData(xmlData);
  QString feedType;
  QDomDocument doc;
  QString errorStr;
  int errorLine;
  int errorColumn;

  QzRegExp rx("encoding=\"([^\"]+)", Qt::CaseInsensitive);
  int pos = rx.indexIn(xmlData);
  if (pos == -1) {
    rx.setPattern("encoding='([^']+)");
    pos = rx.indexIn(xmlData);
  }
  if (pos > -1) {
    QString codecNameT = rx.cap(1);
    qDebug() << "Codec name (1):" << codecNameT;
    QTextCodec *codec = QTextCodec::codecForName(codecNameT.toUtf8());
    if (codec) {
      convertData = codec->toUnicode(xmlData);
    } else {
      qWarning() << "Codec not found (1): " << codecNameT << feedUrl;
      if (codecNameT.contains("us-ascii", Qt::CaseInsensitive)) {
        QString str(xmlData);
        convertData = str.remove(rx.cap(0)+"\"");
      }
    }
  } else {
    if (!codecName.isEmpty()) {
      qDebug() << "Codec name (2):" << codecName;
      QTextCodec *codec = QTextCodec::codecForName(codecName.toUtf8());
      if (codec) {
        convertData = codec->toUnicode(xmlData);
        codecOk = true;
      } else {
        qWarning() << "Codec not found (2): " << codecName << feedUrl;
      }
    }
    if (!codecOk) {
      codecOk = false;
      QStringList codecNameList;
      codecNameList << "UTF-8" << "Windows-1251" << "KOI8-R" << "KOI8-U"
                    << "ISO 8859-5" << "IBM 866";
      foreach (QString codecNameT, codecNameList) {
        QTextCodec *codec = QTextCodec::codecForName(codecNameT.toUtf8());
        if (codec && codec->canEncode(xmlData)) {
          qDebug() << "Codec name (3):" << codecNameT;
          convertData = codec->toUnicode(xmlData);
          codecOk = true;
          break;
        }
      }
      if (!codecOk) {
        convertData = QString::fromLocal8Bit(xmlData);
      }
    }
void IPTVChannelFetcher::run(void)
{
    _thread_running = true;

    // Step 1/4 : Get info from DB
    QString url = CardUtil::GetVideoDevice(_cardid);

    if (_stop_now || url.isEmpty())
    {
        LOG(VB_CHANNEL, LOG_INFO, "Playlist URL was empty");
        _thread_running = false;
        _stop_now = true;
        return;
    }

    LOG(VB_CHANNEL, LOG_INFO, QString("Playlist URL: %1").arg(url));

    // Step 2/4 : Download
    if (_scan_monitor)
    {
        _scan_monitor->ScanPercentComplete(5);
        _scan_monitor->ScanAppendTextToLog(QObject::tr("Downloading Playlist"));
    }

    QString playlist = DownloadPlaylist(url, true);

    if (_stop_now || playlist.isEmpty())
    {
        _thread_running = false;
        _stop_now = true;
        return;
    }

    // Step 3/4 : Process
    if (_scan_monitor)
    {
        _scan_monitor->ScanPercentComplete(35);
        _scan_monitor->ScanAppendTextToLog(QObject::tr("Processing Playlist"));
    }

    const fbox_chan_map_t channels = ParsePlaylist(playlist, this);

    // Step 4/4 : Finish up
    if (_scan_monitor)
        _scan_monitor->ScanAppendTextToLog(QObject::tr("Adding Channels"));
    SetTotalNumChannels(channels.size());

    LOG(VB_CHANNEL, LOG_INFO, QString("Found %1 channels")
        .arg(channels.size()));

    fbox_chan_map_t::const_iterator it = channels.begin();
    for (uint i = 1; it != channels.end(); ++it, ++i)
    {
        QString channum = it.key();
        QString name    = (*it).m_name;
        QString xmltvid = (*it).m_xmltvid.isEmpty() ? "" : (*it).m_xmltvid;
        QString msg = QObject::tr("Channel #%1 : %2").arg(channum).arg(name);

        LOG(VB_CHANNEL, LOG_INFO, QString("Handling channel %1 %2")
            .arg(channum).arg(name));

        int chanid = ChannelUtil::GetChanID(_sourceid, channum);
        if (chanid <= 0)
        {
            if (_scan_monitor)
            {
                _scan_monitor->ScanAppendTextToLog(
                    QObject::tr("Adding %1").arg(msg));
            }
            chanid = ChannelUtil::CreateChanID(_sourceid, channum);
            ChannelUtil::CreateChannel(
                0, _sourceid, chanid, name, name, channum,
                0, 0, 0, false, false, false, QString::null,
                QString::null, "Default", xmltvid);
            ChannelUtil::CreateIPTVTuningData(chanid, (*it).m_tuning);
        }
        else
        {
            if (_scan_monitor)
            {
                _scan_monitor->ScanAppendTextToLog(
                    QObject::tr("Updating %1").arg(msg));
            }
            ChannelUtil::UpdateChannel(
                0, _sourceid, chanid, name, name, channum,
                0, 0, 0, false, false, false, QString::null,
                QString::null, "Default", xmltvid);
            ChannelUtil::UpdateIPTVTuningData(chanid, (*it).m_tuning);
        }

        SetNumChannelsInserted(i);
    }

    if (_scan_monitor)
    {
        _scan_monitor->ScanAppendTextToLog(QObject::tr("Done"));
        _scan_monitor->ScanAppendTextToLog("");
        _scan_monitor->ScanPercentComplete(100);
        _scan_monitor->ScanComplete();
    }

    _thread_running = false;
    _stop_now = true;
}
Example #20
0
/*!
    \since 5.0

    Refreshes \a row in the model with values from the database table row matching
    on primary key values. Without a primary key, all column values must match. If
    no matching row is found, the model will show an empty row.

    Returns \c true if successful; otherwise returns \c false.

    \sa select()
*/
bool QSqlTableModel::selectRow(int row)
{
    Q_D(QSqlTableModel);

    if (row < 0 || row >= rowCount())
        return false;

    const int table_sort_col = d->sortColumn;
    d->sortColumn = -1;
    const QString table_filter = d->filter;
    d->filter = d->db.driver()->sqlStatement(QSqlDriver::WhereStatement,
                                              d->tableName,
                                              primaryValues(row),
                                              false);
    static const QString wh = Sql::where() + Sql::sp();
    if (d->filter.startsWith(wh, Qt::CaseInsensitive))
        d->filter.remove(0, wh.length());

    QString stmt;

    if (!d->filter.isEmpty())
        stmt = selectStatement();

    d->sortColumn = table_sort_col;
    d->filter = table_filter;

    if (stmt.isEmpty())
        return false;

    bool exists;
    QSqlRecord newValues;

    {
        QSqlQuery q(d->db);
        q.setForwardOnly(true);
        if (!q.exec(stmt))
            return false;

        exists = q.next();
        newValues = q.record();
    }

    bool needsAddingToCache = !exists || d->cache.contains(row);

    if (!needsAddingToCache) {
        const QSqlRecord curValues = record(row);
        needsAddingToCache = curValues.count() != newValues.count();
        if (!needsAddingToCache) {
            // Look for changed values. Primary key fields are customarily first
            // and probably change less often than other fields, so start at the end.
            for (int f = curValues.count() - 1; f >= 0; --f) {
                if (curValues.value(f) != newValues.value(f))
                    needsAddingToCache = true;
                    break;
            }
        }
    }

    if (needsAddingToCache) {
        d->cache[row].refresh(exists, newValues);
        emit headerDataChanged(Qt::Vertical, row, row);
        emit dataChanged(createIndex(row, 0), createIndex(row, columnCount() - 1));
    }

    return true;
}
Example #21
0
QVariant
QMacPasteboard::retrieveData(const QString &format, QVariant::Type) const
{
    if (!paste)
        return QVariant();

    sync();

    ItemCount cnt = 0;
    if(PasteboardGetItemCount(paste, &cnt) || !cnt)
        return QByteArray();

#ifdef DEBUG_PASTEBOARD
    qDebug("Pasteboard: retrieveData [%s]", qPrintable(format));
#endif
    const QList<QMacPasteboardMime *> mimes = QMacPasteboardMime::all(mime_type);
    for(int mime = 0; mime < mimes.size(); ++mime) {
        QMacPasteboardMime *c = mimes.at(mime);
        QString c_flavor = c->flavorFor(format);
        if(!c_flavor.isEmpty()) {
            // Handle text/plain a little differently. Try handling Unicode first.
            bool checkForUtf16 = (c_flavor == QLatin1String("com.apple.traditional-mac-plain-text")
                                  || c_flavor == QLatin1String("public.utf8-plain-text"));
            if (checkForUtf16 || c_flavor == QLatin1String("public.utf16-plain-text")) {
                // Try to get the NSStringPboardType from NSPasteboard, newlines are mapped
                // correctly (as '\n') in this data. The 'public.utf16-plain-text' type
                // usually maps newlines to '\r' instead.
                QString str = qt_mac_get_pasteboardString(paste);
                if (!str.isEmpty())
                    return str;
            }
            if (checkForUtf16 && hasFlavor(QLatin1String("public.utf16-plain-text")))
                c_flavor = QLatin1String("public.utf16-plain-text");

            QVariant ret;
            QList<QByteArray> retList;
            for(uint index = 1; index <= cnt; ++index) {
                PasteboardItemID id;
                if(PasteboardGetItemIdentifier(paste, index, &id) != noErr)
                    continue;

                QCFType<CFArrayRef> types;
                if(PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
                    continue;

                const int type_count = CFArrayGetCount(types);
                for(int i = 0; i < type_count; ++i) {
                    CFStringRef flavor = static_cast<CFStringRef>(CFArrayGetValueAtIndex(types, i));
                    if(c_flavor == QCFString::toQString(flavor)) {
                        QCFType<CFDataRef> macBuffer;
                        if(PasteboardCopyItemFlavorData(paste, id, flavor, &macBuffer) == noErr) {
                            QByteArray buffer((const char *)CFDataGetBytePtr(macBuffer), CFDataGetLength(macBuffer));
                            if(!buffer.isEmpty()) {
#ifdef DEBUG_PASTEBOARD
                                qDebug("  - %s [%s] (%s)", qPrintable(format), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName()));
#endif
                                buffer.detach(); //detach since we release the macBuffer
                                retList.append(buffer);
                                break; //skip to next element
                            }
                        }
                    } else {
#ifdef DEBUG_PASTEBOARD
                        qDebug("  - NoMatch %s [%s] (%s)", qPrintable(c_flavor), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName()));
#endif
                    }
                }
            }

            if (!retList.isEmpty()) {
                ret = c->convertToMime(format, retList, c_flavor);
                return ret;
            }
        }
    }
    return QVariant();
}
Example #22
0
bool cMediaInfo::readFromFile(const QString& szFileName)
{
	clear();

	QFileInfo	fileInfo(szFileName);
	if(!fileInfo.exists())
		return(false);

	if(!fileInfo.suffix().compare("APE", Qt::CaseInsensitive))
		m_fileType	= MEDIA_TYPE_APE;
	else if(!fileInfo.suffix().compare("WMA", Qt::CaseInsensitive))
		m_fileType	= MEDIA_TYPE_ASF;
	else if(!fileInfo.suffix().compare("FLAC", Qt::CaseInsensitive))
		m_fileType	= MEDIA_TYPE_FLAC;
	else if(!fileInfo.suffix().compare("AAC", Qt::CaseInsensitive))
		m_fileType	= MEDIA_TYPE_MP4;
	else if(!fileInfo.suffix().compare("MP4", Qt::CaseInsensitive))
		m_fileType	= MEDIA_TYPE_MP4;
	else if(!fileInfo.suffix().compare("M4A", Qt::CaseInsensitive))
		m_fileType	= MEDIA_TYPE_MP4;
	else if(!fileInfo.suffix().compare("MPC", Qt::CaseInsensitive))
		m_fileType	= MEDIA_TYPE_MPC;
	else if(!fileInfo.suffix().compare("MP1", Qt::CaseInsensitive))
		m_fileType	= MEDIA_TYPE_MPEG;
	else if(!fileInfo.suffix().compare("MP2", Qt::CaseInsensitive))
		m_fileType	= MEDIA_TYPE_MPEG;
	else if(!fileInfo.suffix().compare("MP3", Qt::CaseInsensitive))
		m_fileType	= MEDIA_TYPE_MPEG;
	else if(!fileInfo.suffix().compare("TTA", Qt::CaseInsensitive))
		m_fileType	= MEDIA_TYPE_TRUEAUDIO;
	else if(!fileInfo.suffix().compare("WV", Qt::CaseInsensitive))
		m_fileType	= MEDIA_TYPE_WAVPACK;
	else if(!fileInfo.suffix().compare("WAV", Qt::CaseInsensitive))
		m_fileType	= MEDIA_TYPE_WAV;

	if(m_fileType	== MEDIA_TYPE_UNKNOWN)
		return(false);

	m_szFileName					= szFileName;

	ID3v1::Tag*			lpTagV1		= 0;
	ID3v2::Tag*			lpTagV2		= 0;
	APE::Tag*			lpTagAPE	= 0;
	APE::File*			lpApe		= 0;
	ASF::File*			lpASF		= 0;
	FLAC::File*			lpFlac		= 0;
	MP4::File*			lpMP4		= 0;
	MPC::File*			lpMPC		= 0;
	MPEG::File*			lpMPEG		= 0;
	TrueAudio::File*	lpTrueAudio	= 0;
	WavPack::File*		lpWavPack	= 0;
	RIFF::WAV::File*	lpWav		= 0;

	TagLib::PropertyMap	tags;

	QString				szTmp;

	switch(m_fileType)
	{
	case MEDIA_TYPE_APE:
	{
		lpApe	= new APE::File(m_szFileName.toLocal8Bit().data());

		lpTagV1										= lpApe->ID3v1Tag();
		lpTagAPE									= lpApe->APETag();
		tags										= lpApe->properties();

		APE::Properties* lpAudioProperties			= lpApe->audioProperties();

		if(lpAudioProperties)
		{
			m_iLength								= lpAudioProperties->length();
			m_iBitrate								= lpAudioProperties->bitrate();
			m_iSampleRate							= lpAudioProperties->sampleRate();
			m_iChannels								= lpAudioProperties->channels();
			m_iBitsPerSample						= lpAudioProperties->bitsPerSample();
			m_iVersion								= lpAudioProperties->version();
		}
		break;
	}
	case MEDIA_TYPE_ASF:
	{
		lpASF	= new ASF::File(m_szFileName.toLocal8Bit().data());
		TagLib::ASF::Tag*	lpTag					= lpASF->tag();
		m_szTitle									= QString::fromStdWString(lpTag->title().toWString());
		szTmp										= QString::fromStdWString(lpTag->artist().toWString());
		if(!szTmp.isEmpty() && m_bID3V1)
			m_szArtistList							= szTmp.split("\n");
		m_szAlbum									= QString::fromStdWString(lpTag->album().toWString());
		m_szComment									= QString::fromStdWString(lpTag->comment().toWString());
		szTmp										= QString::fromStdWString(lpTag->genre().toWString());
		if(!szTmp.isEmpty() && m_bID3V1)
			m_szGenreList							= szTmp.split("\n");
		m_szRating									= QString::fromStdWString(lpTag->genre().toWString());
		m_szCopyright								= QString::fromStdWString(lpTag->copyright().toWString());
		m_iYear										= lpTag->year();
		m_szTrackNumber								= QString("%1").arg(lpTag->track());

		tags										= lpASF->properties();

		ASF::Properties* lpAudioProperties			= lpASF->audioProperties();

		if(lpAudioProperties)
		{
			m_iLength								= lpAudioProperties->length();
			m_iBitrate								= lpAudioProperties->bitrate();
			m_iSampleRate							= lpAudioProperties->sampleRate();
			m_iChannels								= lpAudioProperties->channels();
			m_bIsEncrypted							= lpAudioProperties->isEncrypted();
		}
		break;
	}
	case MEDIA_TYPE_FLAC:
	{
		lpFlac	= new FLAC::File(m_szFileName.toLocal8Bit().data());
		lpTagV1										= lpFlac->ID3v1Tag();
		lpTagV2										= lpFlac->ID3v2Tag();
		tags										= lpFlac->properties();

		FLAC::Properties* lpAudioProperties			= lpFlac->audioProperties();

		if(lpAudioProperties)
		{
			m_iLength								= lpAudioProperties->length();
			m_iBitrate								= lpAudioProperties->bitrate();
			m_iSampleRate							= lpAudioProperties->sampleRate();
			m_iChannels								= lpAudioProperties->channels();
			m_iSampleWidth							= lpAudioProperties->sampleWidth();
			m_ullSampleFrames						= lpAudioProperties->sampleFrames();
		}
		break;
	}
	case MEDIA_TYPE_MP4:
	{
		lpMP4	= new MP4::File(m_szFileName.toLocal8Bit().data());
		TagLib::MP4::Tag*	lpTag					= lpMP4->tag();
		m_szTitle									= QString::fromStdWString(lpTag->title().toWString());
		szTmp										= QString::fromStdWString(lpTag->artist().toWString());
		if(!szTmp.isEmpty() && m_bID3V1)
			m_szArtistList							= szTmp.split("\n");
		m_szAlbum									= QString::fromStdWString(lpTag->album().toWString());
		m_szComment									= QString::fromStdWString(lpTag->comment().toWString());
		szTmp										= QString::fromStdWString(lpTag->genre().toWString());
		if(!szTmp.isEmpty() && m_bID3V1)
			m_szGenreList							= szTmp.split("\n");
		m_iYear										= lpTag->year();
		m_szTrackNumber								= QString("%1").arg(lpTag->track());

		tags										= lpMP4->properties();

		MP4::Properties* lpAudioProperties			= lpMP4->audioProperties();

		if(lpAudioProperties)
		{
			m_iLength								= lpAudioProperties->length();
			m_iBitrate								= lpAudioProperties->bitrate();
			m_iSampleRate							= lpAudioProperties->sampleRate();
			m_iChannels								= lpAudioProperties->channels();
			m_iBitsPerSample						= lpAudioProperties->bitsPerSample();
			m_bIsEncrypted							= lpAudioProperties->isEncrypted();
		}
		break;
	}
	case MEDIA_TYPE_MPC:
	{
		lpMPC	= new MPC::File(m_szFileName.toLocal8Bit().data());
		lpTagV1										= lpMPC->ID3v1Tag();
		lpTagAPE									= lpMPC->APETag();
		tags										= lpMPC->properties();

		MPC::Properties* lpAudioProperties			= lpMPC->audioProperties();

		if(lpAudioProperties)
		{
			m_iLength								= lpAudioProperties->length();
			m_iBitrate								= lpAudioProperties->bitrate();
			m_iSampleRate							= lpAudioProperties->sampleRate();
			m_iChannels								= lpAudioProperties->channels();
			m_iVersion								= lpAudioProperties->mpcVersion();
			m_ullSampleFrames						= lpAudioProperties->sampleFrames();
			m_iTrackGain							= lpAudioProperties->trackGain();
			m_iAlbumGain							= lpAudioProperties->albumGain();
			m_iTrackPeak							= lpAudioProperties->trackPeak();
			m_iAlbumPeak							= lpAudioProperties->albumPeak();
		}
		break;
	}
	case MEDIA_TYPE_MPEG:
	{
		lpMPEG	= new MPEG::File(m_szFileName.toLocal8Bit().data());

		lpTagV1										= lpMPEG->ID3v1Tag();
		lpTagV2										= lpMPEG->ID3v2Tag();
		lpTagAPE									= lpMPEG->APETag();
		tags										= lpMPEG->properties();

		MPEG::Properties*	lpAudioProperties		= lpMPEG->audioProperties();

		if(lpAudioProperties)
		{
			m_iLength								= lpAudioProperties->length();
			m_iBitrate								= lpAudioProperties->bitrate();
			m_iSampleRate							= lpAudioProperties->sampleRate();
			m_iChannels								= lpAudioProperties->channels();
			m_iLayer								= lpAudioProperties->layer();
			switch(lpAudioProperties->version())
			{
			case MPEG::Header::Version1:
				m_iVersion	= 10;
				break;
			case MPEG::Header::Version2:
				m_iVersion	= 20;
				break;
			case MPEG::Header::Version2_5:
				m_iVersion	= 25;
				break;
			}
			m_bProtectionEnabled					= lpAudioProperties->protectionEnabled();
			switch(lpAudioProperties->channelMode())
			{
			case MPEG::Header::Stereo:
				m_channelMode						= CHANNEL_MODE_STEREO;
				break;
			case MPEG::Header::JointStereo:
				m_channelMode						= CHANNEL_MODE_JOINTSTEREO;
				break;
			case MPEG::Header::DualChannel:
				m_channelMode						= CHANNEL_MODE_DUALMONO;
				break;
			case MPEG::Header::SingleChannel:
				m_channelMode						= CHANNEL_MODE_MONO;
				break;
			}
			m_bIsCopyrighted						= lpAudioProperties->isCopyrighted();
			m_bIsOriginal							= lpAudioProperties->isOriginal();
		}
		break;
	}
	case MEDIA_TYPE_TRUEAUDIO:
	{
		lpTrueAudio	= new TrueAudio::File(m_szFileName.toLocal8Bit().data());
		lpTagV1										= lpTrueAudio->ID3v1Tag();
		lpTagV2										= lpTrueAudio->ID3v2Tag();
		tags										= lpTrueAudio->properties();

		TrueAudio::Properties* lpAudioProperties	= lpTrueAudio->audioProperties();

		if(lpAudioProperties)
		{
			m_iLength								= lpAudioProperties->length();
			m_iBitrate								= lpAudioProperties->bitrate();
			m_iSampleRate							= lpAudioProperties->sampleRate();
			m_iChannels								= lpAudioProperties->channels();
			m_iBitsPerSample						= lpAudioProperties->bitsPerSample();
			m_iVersion								= lpAudioProperties->ttaVersion();
		}
		break;
	}
	case MEDIA_TYPE_WAVPACK:
	{
		lpWavPack	= new WavPack::File(m_szFileName.toLocal8Bit().data());
		lpTagV1										= lpWavPack->ID3v1Tag();
		lpTagAPE									= lpWavPack->APETag();
		tags										= lpWavPack->properties();

		WavPack::Properties* lpAudioProperties		= lpWavPack->audioProperties();

		if(lpAudioProperties)
		{
			m_iLength								= lpAudioProperties->length();
			m_iBitrate								= lpAudioProperties->bitrate();
			m_iSampleRate							= lpAudioProperties->sampleRate();
			m_iChannels								= lpAudioProperties->channels();
			m_iBitsPerSample						= lpAudioProperties->bitsPerSample();
			m_ullSampleFrames						= lpAudioProperties->sampleFrames();
			m_iVersion								= lpAudioProperties->version();
		}
		break;
	}
	case MEDIA_TYPE_WAV:
	{
		lpWav	= new RIFF::WAV::File(m_szFileName.toLocal8Bit().data());
		lpTagV2										= lpWav->tag();
		tags										= lpWav->properties();

		RIFF::WAV::Properties* lpAudioProperties	= lpWav->audioProperties();

		if(lpAudioProperties)
		{
			m_iLength								= lpAudioProperties->length();
			m_iBitrate								= lpAudioProperties->bitrate();
			m_iSampleRate							= lpAudioProperties->sampleRate();
			m_iChannels								= lpAudioProperties->channels();
			m_iSampleWidth							= lpAudioProperties->sampleWidth();
			m_ullSampleFrames						= lpAudioProperties->sampleFrames();
		}
		break;
	}
	default:
		break;
	}

	if(lpTagV2 && m_bID3V2)
		readTagV2(lpTagV2);
	if(lpTagV1 && m_bID3V1)
		readTagV1(lpTagV1);
	if(lpTagAPE && m_bAPE)
		readTagAPE(lpTagAPE);
	if(m_bProperties)
		readTagProperties(tags);

	if(lpApe)
		delete lpApe;
	if(lpASF)
		delete lpASF;
	if(lpFlac)
		delete lpFlac;
	if(lpMP4)
		delete lpMP4;
	if(lpMPC)
		delete lpMPC;
	if(lpMPEG)
		delete lpMPEG;
	if(lpTrueAudio)
		delete lpTrueAudio;
	if(lpWavPack)
		delete lpWavPack;
	if(lpWav)
		delete lpWav;

	m_bIsValid	= true;
	return(true);
}
Example #23
0
QgsMapLayer* QgsRemoteOWSBuilder::createMapLayer(
  const QDomElement& elem,
  const QString& layerName,
  QList<QTemporaryFile*>& filesToRemove,
  QList<QgsMapLayer*>& layersToRemove, bool allowCaching ) const
{
  if ( elem.isNull() )
  {
    return 0;
  }

  //parse service element
  QDomNode serviceNode = elem.namedItem( "Service" );
  if ( serviceNode.isNull() )
  {
    QgsDebugMsg( "No <Service> node found, returning 0" );
    return 0; //service node is necessary
  }

  //parse OnlineResource element
  QDomNode onlineResourceNode = elem.namedItem( "OnlineResource" );
  if ( onlineResourceNode.isNull() )
  {
    QgsDebugMsg( "No <OnlineResource> element, returning 0" );
    return 0;
  }

  //get uri
  QDomElement onlineResourceElement = onlineResourceNode.toElement();
  QString url = onlineResourceElement.attribute( "href" );

  QgsMapLayer* result = 0;
  QString serviceName = serviceNode.toElement().text();

  //append missing ? or & at the end of the url, but only for WFS and WMS
  if ( serviceName == "WFS" || serviceName == "WMS" )
  {
    if ( !url.endsWith( "?" ) && !url.endsWith( "&" ) )
    {
      if ( url.contains( "?" ) )
      {
        url.append( "&" );
      }
      else
      {
        url.append( "?" );
      }
    }
  }


  if ( serviceName == "WFS" )
  {
    //support for old format where type is explicitly given and not part of url
    QString tname = onlineResourceElement.attribute( "type" );
    if ( !tname.isEmpty() )
    {
      url.append( "SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=" + tname );
    }

    if ( allowCaching )
    {
      result = QgsMSLayerCache::instance()->searchLayer( url, layerName );
    }
    if ( result )
    {
      return result;
    }
    result = new QgsVectorLayer( url, layerNameFromUri( url ), "WFS" );
    if ( result->isValid() )
    {
      if ( allowCaching )
      {
        QgsMSLayerCache::instance()->insertLayer( url, layerName, result );
      }
      else
      {
        layersToRemove.push_back( result );
      }
    }
  }
  else if ( serviceName == "WMS" )
  {
    result = wmsLayerFromUrl( url, layerName, layersToRemove, allowCaching );
  }
  else if ( serviceName == "WCS" )
  {
    QgsDebugMsg( "Trying to get WCS layer" );
    result = wcsLayerFromUrl( url, layerName, filesToRemove, layersToRemove );
  }
  else if ( serviceName == "SOS" )
  {
    result = sosLayer( elem, url, layerName, layersToRemove, allowCaching );
  }

  if ( !result || !result->isValid() )
  {
    QgsDebugMsg( "Error, maplayer is 0 or invalid" );
    if ( result )
    {
      delete result;
    }
    return 0;
  }

  return result;
}
Example #24
0
void Top_Menu::print_file_name_changed(QString filename)
{
    print_button_->setDisabled(filename.isEmpty());
    return;
}
Example #25
0
QPair<QString, QString> GetOSNameSplit ()
{
#if defined(Q_OS_MAC)
    QSysInfo::MacVersion v = QSysInfo::MacintoshVersion;
    if (v == QSysInfo::MV_10_3)
        return SplitInfo_t ("Mac OS X", "10.3");
    else if (v == QSysInfo::MV_10_4)
        return SplitInfo_t ("Mac OS X", "10.4");
    else if (v == QSysInfo::MV_10_5)
        return SplitInfo_t ("Mac OS X", "10.5");
    else if (v == QSysInfo::MV_10_6)
        return SplitInfo_t ("Mac OS X", "10.6");
    else if (v == QSysInfo::MV_10_7)
        return SplitInfo_t ("Mac OS X", "10.7");
    else
        return SplitInfo_t ("Mac OS X", "Unknown version");
#elif defined(Q_OS_WIN32)
    QSysInfo::WinVersion v = QSysInfo::WindowsVersion;
    if (v == QSysInfo::WV_95)
        return SplitInfo_t ("Windows", "95");
    else if (v == QSysInfo::WV_98)
        return SplitInfo_t ("Windows", "98");
    else if (v == QSysInfo::WV_Me)
        return SplitInfo_t ("Windows", "Me");
    else if (v == QSysInfo::WV_DOS_based)
        return SplitInfo_t ("Windows", "9x/Me");
    else if (v == QSysInfo::WV_NT)
        return SplitInfo_t ("Windows", "NT 4.x");
    else if (v == QSysInfo::WV_2000)
        return SplitInfo_t ("Windows", "2000");
    else if (v == QSysInfo::WV_XP)
        return SplitInfo_t ("Windows", "XP");
    else if (v == QSysInfo::WV_2003)
        return SplitInfo_t ("Windows", "2003");
    else if (v == QSysInfo::WV_VISTA)
        return SplitInfo_t ("Windows", "Vista");
    else if (v == QSysInfo::WV_WINDOWS7)
        return SplitInfo_t ("Windows", "7");
    else if (v == 0x00a0)
        return SplitInfo_t ("Windows", "8");
    else if (v == QSysInfo::WV_NT_based)
        return SplitInfo_t ("Windows", "NT-based");
#else
    QString osName;

    QProcess proc;
    proc.start (QString ("/bin/sh"),
                QStringList ("-c") << "lsb_release -ds", QIODevice::ReadOnly);
    if (proc.waitForStarted ())
    {
        QTextStream stream (&proc);
        QString ret;
        while (proc.waitForReadyRead ())
            ret += stream.readAll ();
        proc.close ();
        if (!ret.isEmpty ())
            osName = ret.remove ('"').trimmed ();
    }

    if (osName.isEmpty ())
    {
        struct OsInfo_t
        {
            QString path;
            QString name;
        } OsInfo [] =
        {
            { "/etc/mandrake-release", "Mandrake Linux" },
            { "/etc/debian_version", "Debian GNU/Linux" },
            { "/etc/gentoo-release", "Gentoo Linux" },
            { "/etc/exherbo-release", "Exherbo" },
            { "/etc/arch-release", "Arch Linux" },
            { "/etc/slackware-version", "Slackware Linux" },
            { "/etc/pld-release", "" },
            { "/etc/lfs-release", "LFS" },
            { "/etc/SuSE-release", "SuSE linux" },
            { "/etc/conectiva-release", "Connectiva" },
            { "/etc/.installed", "" },
            { "/etc/redhat-release", "" },
            { "", "" }
        };
        OsInfo_t *osptr = OsInfo;
        while (!osptr->path.isEmpty ())
        {
            QFileInfo fi (osptr->path);
            if (fi.exists ())
            {
                QFile f (osptr->path);
                f.open (QIODevice::ReadOnly);
                QString data = QString (f.read (1024)).trimmed ();
                if (osptr->name.isEmpty ())
                    osName = data;
                else
                    osName = QString ("%1 (%2)")
                             .arg (osptr->name)
                             .arg (data);
                break;
            }
            ++osptr;
        }
    }

    utsname u;
    uname (&u);

    return qMakePair (osName.isEmpty () ? QString (u.sysname) : osName,
                      QString ("%1 %2 %3").arg (u.machine, u.release, u.version));
#endif

    return qMakePair (QString ("Unknown OS"), QString ("Unknown version"));
}
Example #26
0
void UserSubWindow::showInformationBox(const QString &message) const {
  if (!message.isEmpty()) {
    QMessageBox::information(const_cast<UserSubWindow *>(this),
                             this->windowTitle(), message);
  }
}
Example #27
0
bool PathChooser::validatePath(const QString &path, QString *errorMessage)
{
    QString expandedPath = d->expandedPath(path);

    if (path.isEmpty()) {
        if (errorMessage)
            *errorMessage = tr("The path must not be empty.");
        return false;
    }

    if (expandedPath.isEmpty()) {
        if (errorMessage)
            *errorMessage = tr("The path '%1' expanded to an empty string.").arg(QDir::toNativeSeparators(path));
        return false;
    }
    const QFileInfo fi(expandedPath);

    // Check if existing
    switch (d->m_acceptingKind) {
    case PathChooser::ExistingDirectory: // fall through
        if (!fi.exists()) {
            if (errorMessage)
                *errorMessage = tr("The path '%1' does not exist.").arg(QDir::toNativeSeparators(expandedPath));
            return false;
        }
        if (!fi.isDir()) {
            if (errorMessage)
                *errorMessage = tr("The path '%1' is not a directory.").arg(QDir::toNativeSeparators(expandedPath));
            return false;
        }
        break;
    case PathChooser::File: // fall through
        if (!fi.exists()) {
            if (errorMessage)
                *errorMessage = tr("The path '%1' does not exist.").arg(QDir::toNativeSeparators(expandedPath));
            return false;
        }
        break;
    case PathChooser::SaveFile:
        if (!fi.absoluteDir().exists()) {
            if (errorMessage)
                *errorMessage = tr("The directory '%1' does not exist.").arg(QDir::toNativeSeparators(fi.absolutePath()));
            return false;
        }
        break;
    case PathChooser::ExistingCommand:
        if (!fi.exists()) {
            if (errorMessage)
                *errorMessage = tr("The path '%1' does not exist.").arg(QDir::toNativeSeparators(expandedPath));
            return false;
        }
        if (!fi.isExecutable()) {
            if (errorMessage)
                *errorMessage = tr("Cannot execute '%1'.").arg(QDir::toNativeSeparators(expandedPath));
            return false;
        }
        break;
    case PathChooser::Directory:
        if (fi.exists() && !fi.isDir()) {
            if (errorMessage)
                *errorMessage = tr("The path '%1' is not a directory.").arg(QDir::toNativeSeparators(expandedPath));
            return false;
        }
        break;
    case PathChooser::Command: // fall through
        if (fi.exists() && !fi.isExecutable()) {
            if (errorMessage)
                *errorMessage = tr("Cannot execute '%1'.").arg(QDir::toNativeSeparators(expandedPath));
            return false;
        }
        break;

    default:
        ;
    }

    // Check expected kind
    switch (d->m_acceptingKind) {
    case PathChooser::ExistingDirectory:
        if (!fi.isDir()) {
            if (errorMessage)
                *errorMessage = tr("The path <b>%1</b> is not a directory.").arg(QDir::toNativeSeparators(expandedPath));
            return false;
        }
        break;

    case PathChooser::File:
        if (!fi.isFile()) {
            if (errorMessage)
                *errorMessage = tr("The path <b>%1</b> is not a file.").arg(QDir::toNativeSeparators(expandedPath));
            return false;
        }
        break;

    case PathChooser::SaveFile:
        if (fi.exists() && fi.isDir()) {
            if (errorMessage)
                *errorMessage = tr("The path <b>%1</b> is not a file.").arg(QDir::toNativeSeparators(fi.absolutePath()));
            return false;
        }
        break;

    case PathChooser::ExistingCommand:
        if (!fi.isFile() || !fi.isExecutable()) {
            if (errorMessage)
                *errorMessage = tr("The path <b>%1</b> is not an executable file.").arg(QDir::toNativeSeparators(expandedPath));
            return false;
        }

    case PathChooser::Command:
        break;

    case PathChooser::Any:
        break;

    default:
        ;
    }
    if (errorMessage)
        *errorMessage = tr("Full path: <b>%1</b>").arg(QDir::toNativeSeparators(expandedPath));
    return true;
}
void QgsDataDefinedButton::menuActionTriggered( QAction* action )
{
  if ( action == mActionActive )
  {
    setActive( mActionActive->data().toBool() );
    updateGui();
  }
  else if ( action == mActionDescription )
  {
    showDescriptionDialog();
  }
  else if ( action == mActionExpDialog )
  {
    showExpressionDialog();
  }
  else if ( action == mActionExpression )
  {
    setUseExpression( true );
    setActive( true );
    updateGui();
  }
  else if ( action == mActionCopyExpr )
  {
    QApplication::clipboard()->setText( getExpression() );
  }
  else if ( action == mActionPasteExpr )
  {
    QString exprString = QApplication::clipboard()->text();
    if ( !exprString.isEmpty() )
    {
      setExpression( exprString );
      setUseExpression( true );
      setActive( true );
      updateGui();
    }
  }
  else if ( action == mActionClearExpr )
  {
    // only deactivate if defined expression is being used
    if ( isActive() && useExpression() )
    {
      setUseExpression( false );
      setActive( false );
    }
    setExpression( QString( "" ) );
    updateGui();
  }
  else if ( mFieldsMenu->actions().contains( action ) )  // a field name clicked
  {
    if ( action->isEnabled() )
    {
      if ( getField() != action->text() )
      {
        setField( action->data().toString() );
      }
      setUseExpression( false );
      setActive( true );
      updateGui();
    }
  }
}
void SaveAsImageDialog::accept() {
    const QString fileName = ui->name->text();
    if (fileName.isEmpty())
        return;

    if (QFile::exists(fileName)) {
        const QMessageBox::StandardButton button =
                QMessageBox::warning(this,
                                     tr("Save as Image"),
                                     tr("%1 already exists.\n"
                                        "Do you want to replace it?")
                                     .arg(QFileInfo(fileName).fileName()),
                                     QMessageBox::Yes | QMessageBox::No,
                                     QMessageBox::No);

        if (button != QMessageBox::Yes)
            return;
    }

    const bool visibleLayersOnly = ui->visibleLayers->isChecked();
    const bool useCurrentScale = ui->currentZoomLevel->isChecked();
    const bool drawTileGrid = ui->showGrid->isChecked();

    MapRenderer *renderer = mMapEditor->renderer();

    //remember the current render flags
    const Aurora::RenderFlags renderFlags = renderer->flags();

    renderer->setFlag(ShowTileObjectOutlines, false);

    QSize mapSize = renderer->mapSize();
    if (useCurrentScale)
        mapSize *= mCurrentScale;

    QImage image(mapSize, QImage::Format_ARGB32);
    image.fill(Qt::transparent);
    QPainter painter(&image);

    if (useCurrentScale && mCurrentScale != qreal(1)) {
        painter.setRenderHints(QPainter::SmoothPixmapTransform |
                               QPainter::HighQualityAntialiasing);
        painter.setTransform(QTransform::fromScale(mCurrentScale,
                                                   mCurrentScale));
    }

    foreach (const Layer *layer, mMapEditor->map()->layers()) {
        if (visibleLayersOnly && !layer->isVisible())
            continue;

        painter.setOpacity(layer->opacity());

        const Tilelayer *tilelayer = dynamic_cast<const Tilelayer*>(layer);

        if (tilelayer) {
            renderer->drawTilelayer(&painter, tilelayer);
        }
    }

    if (drawTileGrid) {
        renderer->drawGrid(&painter, QRectF(QPointF(), renderer->mapSize()));
    }

    //restore the previous render flags
    renderer->setFlags(renderFlags);

    image.save(fileName);
    mPath = QFileInfo(fileName).path();

    //store settings for next time
    QSettings *s = Preferences::instance()->settings();
    s->setValue(QLatin1String(VISIBLE_ONLY_KEY), visibleLayersOnly);
    s->setValue(QLatin1String(CURRENT_SCALE_KEY), useCurrentScale);
    s->setValue(QLatin1String(DRAW_GRID_KEY), drawTileGrid);

    QDialog::accept();
}
Example #30
0
void IMDB::parseAndAssignInfos(QString html, Movie *movie, QList<int> infos)
{
    QRegExp rx;
    rx.setMinimal(true);

    rx.setPattern("<h1 class=\"header\">[^<]*<span class=\"itemprop\" itemprop=\"name\">([^<]*)</span>");
    if (infos.contains(MovieScraperInfos::Title) && rx.indexIn(html) != -1)
        movie->setName(rx.cap(1));

    rx.setPattern("<h1 itemprop=\"name\" class=\"\">(.*)&nbsp;<span id=\"titleYear\">");
    if (infos.contains(MovieScraperInfos::Title) && rx.indexIn(html) != -1)
        movie->setName(rx.cap(1));

    if (infos.contains(MovieScraperInfos::Director)) {
        rx.setPattern("<div class=\"txt-block\" itemprop=\"director\" itemscope itemtype=\"http://schema.org/Person\">(.*)</div>");
        QString directorsBlock;
        if (rx.indexIn(html) != -1) {
            directorsBlock = rx.cap(1);
        } else {
            rx.setPattern("<div class=\"credit_summary_item\">[^<]*<h4 class=\"inline\">Director:</h4>(.*)</div>");
            if (rx.indexIn(html) != -1)
                directorsBlock = rx.cap(1);
        }

        if (!directorsBlock.isEmpty()) {
            QStringList directors;
            rx.setPattern("<a href=\"[^\"]*\"(.*)itemprop='url'><span class=\"itemprop\" itemprop=\"name\">([^<]*)</span></a>");
            int pos = 0;
            while ((pos = rx.indexIn(directorsBlock, pos)) != -1) {
                directors << rx.cap(2);
                pos += rx.matchedLength();
            }
            movie->setDirector(directors.join(", "));
        }
    }

    if (infos.contains(MovieScraperInfos::Writer)) {
        rx.setPattern("<div class=\"txt-block\" itemprop=\"creator\" itemscope itemtype=\"http://schema.org/Person\">(.*)</div>");
        QString writersBlock;
        if (rx.indexIn(html) != -1) {
            writersBlock = rx.cap(1);
        } else {
            rx.setPattern("<div class=\"credit_summary_item\">[^<]*<h4 class=\"inline\">Writers:</h4>(.*)</div>");
            if (rx.indexIn(html) != -1)
                writersBlock = rx.cap(1);
        }

        if (!writersBlock.isEmpty()) {
            QStringList writers;
            rx.setPattern("<a href=\"[^\"]*\"(.*)itemprop='url'><span class=\"itemprop\" itemprop=\"name\">([^<]*)</span></a>");
            int pos = 0;
            while ((pos = rx.indexIn(writersBlock, pos)) != -1) {
                writers << rx.cap(2);
                pos += rx.matchedLength();
            }
            movie->setWriter(writers.join(", "));
        }
    }

    rx.setPattern("<div class=\"see-more inline canwrap\" itemprop=\"genre\">[^<]*<h4 class=\"inline\">Genres:</h4>(.*)</div>");
    if (infos.contains(MovieScraperInfos::Genres) && rx.indexIn(html) != -1) {
        QString genres = rx.cap(1);
        rx.setPattern("<a href=\"[^\"]*\"[^>]*>([^<]*)</a>");
        int pos = 0;
        while ((pos = rx.indexIn(genres, pos)) != -1) {
            movie->addGenre(Helper::instance()->mapGenre(rx.cap(1).trimmed()));
            pos += rx.matchedLength();
        }
    }

    rx.setPattern("<div class=\"txt-block\">.*<h4 class=\"inline\">Taglines:</h4>(.*)</div>");
    if (infos.contains(MovieScraperInfos::Tagline) && rx.indexIn(html) != -1) {
        QString tagline = rx.cap(1);
        QRegExp rxMore("<span class=\"see-more inline\">.*</span>");
        rxMore.setMinimal(true);
        tagline.remove(rxMore);
        movie->setTagline(tagline.trimmed());
    }

    rx.setPattern("<div class=\"see-more inline canwrap\" itemprop=\"keywords\">(.*)</div>");
    if (infos.contains(MovieScraperInfos::Tags) && rx.indexIn(html) != -1) {
        QString keywords = rx.cap(1);
        rx.setPattern("<span class=\"itemprop\" itemprop=\"keywords\">([^<]*)</span>");
        int pos = 0;
        while ((pos = rx.indexIn(keywords, pos)) != -1) {
            movie->addTag(rx.cap(1).trimmed());
            pos += rx.matchedLength();
        }
    }

    if (infos.contains(MovieScraperInfos::Released)) {
        rx.setPattern("<a href=\"[^\"]*\"(.*)title=\"See all release dates\" >[^<]*<meta itemprop=\"datePublished\" content=\"([^\"]*)\" />");
        if (rx.indexIn(html) != -1) {
            movie->setReleased(QDate::fromString(rx.cap(2), "yyyy-MM-dd"));
        } else {
            rx.setPattern("<h4 class=\"inline\">Release Date:</h4> ([0-9]+) ([A-z]*) ([0-9]{4})");
            if (rx.indexIn(html) != -1) {
                int day = rx.cap(1).trimmed().toInt();
                int month = -1;
                QString monthName = rx.cap(2).trimmed();
                int year = rx.cap(3).trimmed().toInt();
                if (monthName.contains("January", Qt::CaseInsensitive))
                    month = 1;
                else if (monthName.contains("February", Qt::CaseInsensitive))
                    month = 2;
                else if (monthName.contains("March", Qt::CaseInsensitive))
                    month = 3;
                else if (monthName.contains("April", Qt::CaseInsensitive))
                    month = 4;
                else if (monthName.contains("May", Qt::CaseInsensitive))
                    month = 5;
                else if (monthName.contains("June", Qt::CaseInsensitive))
                    month = 6;
                else if (monthName.contains("July", Qt::CaseInsensitive))
                    month = 7;
                else if (monthName.contains("August", Qt::CaseInsensitive))
                    month = 8;
                else if (monthName.contains("September", Qt::CaseInsensitive))
                    month = 9;
                else if (monthName.contains("October", Qt::CaseInsensitive))
                    month = 10;
                else if (monthName.contains("November", Qt::CaseInsensitive))
                    month = 11;
                else if (monthName.contains("December", Qt::CaseInsensitive))
                    month = 12;

                if (day != 0 && month != -1 && year != 0)
                    movie->setReleased(QDate(year, month, day));
            }
        }
    }


    rx.setPattern("<meta itemprop=\"contentRating\" content=\"([^\"]*)\">");
    if (infos.contains(MovieScraperInfos::Certification) && rx.indexIn(html) != -1)
        movie->setCertification(Helper::instance()->mapCertification(rx.cap(1)));

    rx.setPattern("<time itemprop=\"duration\" datetime=\"PT([0-9]+)M\" >");
    if (infos.contains(MovieScraperInfos::Runtime) && rx.indexIn(html) != -1)
        movie->setRuntime(rx.cap(1).toInt());

    rx.setPattern("<h4 class=\"inline\">Runtime:</h4>[^<]*<time itemprop=\"duration\" datetime=\"PT([0-9]+)M\">");
    if (infos.contains(MovieScraperInfos::Runtime) && rx.indexIn(html) != -1)
        movie->setRuntime(rx.cap(1).toInt());

    rx.setPattern("<p itemprop=\"description\">(.*)</p>");
    if (infos.contains(MovieScraperInfos::Overview) && rx.indexIn(html) != -1) {
        QString outline = rx.cap(1).remove(QRegExp("<[^>]*>"));
        outline = outline.remove("See full summary&nbsp;&raquo;").trimmed();
        movie->setOutline(outline);
    }

    rx.setPattern("<div class=\"summary_text\" itemprop=\"description\">(.*)</div>");
    if (infos.contains(MovieScraperInfos::Overview) && rx.indexIn(html) != -1) {
        QString outline = rx.cap(1).remove(QRegExp("<[^>]*>")).trimmed();
        movie->setOutline(outline);
    }

    rx.setPattern("<div class=\"inline canwrap\" itemprop=\"description\">(.*)</div>");
    if (infos.contains(MovieScraperInfos::Overview) && rx.indexIn(html) != -1) {
        QString overview = rx.cap(1).trimmed();
        QRegExp rxWrittenBy("<em class=\"nobr\">.*</em>");
        rxWrittenBy.setMinimal(true);
        overview.remove(rxWrittenBy).remove(QRegExp("<[^>]*>"));
        movie->setOverview(overview.trimmed());
    }

    if (infos.contains(MovieScraperInfos::Rating)) {
        rx.setPattern("<div class=\"star-box-details\" itemtype=\"http://schema.org/AggregateRating\" itemscope itemprop=\"aggregateRating\">(.*)</div>");
        if (rx.indexIn(html) != -1) {
            QString content = rx.cap(1);
            rx.setPattern("<span itemprop=\"ratingValue\">(.*)</span>");
            if (rx.indexIn(content) != -1)
                movie->setRating(rx.cap(1).trimmed().replace(",", ".").toFloat());

            rx.setPattern("<span itemprop=\"ratingCount\">(.*)</span>");
            if (rx.indexIn(content) != -1)
                movie->setVotes(rx.cap(1).replace(",", "").replace(".", "").toInt());
        } else {
            rx.setPattern("<div class=\"imdbRating\" itemtype=\"http://schema.org/AggregateRating\" itemscope=\"\" itemprop=\"aggregateRating\">(.*)</div>");
            if (rx.indexIn(html) != -1) {
                QString content = rx.cap(1);
                rx.setPattern("([0-9]\\.[0-9]) based on ([0-9\\,]*) ");
                if (rx.indexIn(content) != -1) {
                    movie->setRating(rx.cap(1).trimmed().replace(",", ".").toFloat());
                    movie->setVotes(rx.cap(2).replace(",", "").replace(".", "").toInt());
                }
                rx.setPattern("([0-9]\\,[0-9]) based on ([0-9\\.]*) ");
                if (rx.indexIn(content) != -1) {
                    movie->setRating(rx.cap(1).trimmed().replace(",", ".").toFloat());
                    movie->setVotes(rx.cap(2).replace(",", "").replace(".", "").toInt());
                }
            }
        }
    }

    rx.setPattern("<strong>Top 250 #([0-9]+)</strong>");
    if (infos.contains(MovieScraperInfos::Rating) && rx.indexIn(html) != -1)
        movie->setTop250(rx.cap(1).toInt());

    if (infos.contains(MovieScraperInfos::Studios)) {
        rx.setPattern("<span itemprop=\"creator\" itemscope itemtype=\"http://schema.org/Organization\">.*<span class=\"itemprop\" itemprop=\"name\">([^<]*)</span>.*</span>");
        int pos = 0;
        while ((pos = rx.indexIn(html, pos)) != -1) {
            movie->addStudio(Helper::instance()->mapStudio(rx.cap(1).trimmed()));
            pos += rx.matchedLength();
        }
    }

    rx.setPattern("<div class=\"txt-block\">[^<]*<h4 class=\"inline\">Country:</h4>(.*)</div>");
    if (infos.contains(MovieScraperInfos::Countries) && rx.indexIn(html) != -1) {
        QString content = rx.cap(1);
        rx.setPattern("<a href=\"[^\"]*\"[\\n\\s]*itemprop='url'>([^<]*)</a>");
        int pos = 0;
        while ((pos = rx.indexIn(content, pos)) != -1) {
            movie->addCountry(Helper::instance()->mapCountry(rx.cap(1).trimmed()));
            pos += rx.matchedLength();
        }
    }

    rx.setPattern("<table class=\"cast_list\">(.*)</table>");
    if (infos.contains(MovieScraperInfos::Actors) && rx.indexIn(html) != -1) {
        QString content = rx.cap(1);
        rx.setPattern("<tr class=\"[^\"]*\">(.*)</tr>");
        int pos = 0;
        while ((pos = rx.indexIn(content, pos)) != -1) {
            QString actor = rx.cap(1);
            pos += rx.matchedLength();

            Actor a;

            QRegExp rxName("<span class=\"itemprop\" itemprop=\"name\">(.*)</span>");
            rxName.setMinimal(true);
            if (rxName.indexIn(actor) != -1)
                a.name = rxName.cap(1).trimmed();

            QRegExp rxRole("<td class=\"character\">[\\s\\n]*<div>[\\s\\n](.*)[\\s\\n]*</div>");
            rxRole.setMinimal(true);
            if (rxRole.indexIn(actor) != -1) {
                QString role = rxRole.cap(1);
                rxRole.setPattern("<a href=\"[^\"]*\" >(.*)</a>");
                if (rxRole.indexIn(role) != -1)
                    role = rxRole.cap(1);
                a.role = role.trimmed().replace(QRegExp("[\\s\\n]+"), " ");
            }

            QRegExp rxImg("<img [^<]*loadlate=\"([^\"]*)\"[^<]* />");
            rxImg.setMinimal(true);
            if (rxImg.indexIn(actor) != -1) {
                QString img = rxImg.cap(1);
                QRegExp aRx1("http://ia.media-imdb.com/images/(.*)/(.*)._V(.*).jpg");
                aRx1.setMinimal(true);
                if (aRx1.indexIn(img) != -1)
                    a.thumb = "http://ia.media-imdb.com/images/" + aRx1.cap(1) + "/" + aRx1.cap(2) + ".jpg";
                else
                    a.thumb = rxImg.cap(1);
            }

            movie->addActor(a);
        }
    }
}