Exemple #1
0
void VersionBuilder::readInstancePatches()
{
	PatchOrder userOrder;
	readOverrideOrders(m_instance, userOrder);
	QDir patches(instance_root.absoluteFilePath("patches/"));

	// first, load things by sort order.
	for (auto id : userOrder)
	{
		// ignore builtins
		if (id == "net.minecraft")
			continue;
		if (id == "org.lwjgl")
			continue;
		// parse the file
		QString filename = patches.absoluteFilePath(id + ".json");
		QFileInfo finfo(filename);
		if(!finfo.exists())
		{
			QLOG_INFO() << "Patch file " << filename << " was deleted by external means...";
			continue;
		}
		QLOG_INFO() << "Reading" << filename << "by user order";
		auto file = parseJsonFile(finfo, false);
		// sanity check. prevent tampering with files.
		if (file->fileId != id)
		{
			throw VersionBuildError(
				QObject::tr("load id %1 does not match internal id %2").arg(id, file->fileId));
		}
		m_version->VersionPatches.append(file);
	}
	// now load the rest by internal preference.
	QMap<int, QPair<QString, VersionFilePtr>> files;
	for (auto info : patches.entryInfoList(QStringList() << "*.json", QDir::Files))
	{
		// parse the file
		QLOG_INFO() << "Reading" << info.fileName();
		auto file = parseJsonFile(info, true);
		// ignore builtins
		if (file->fileId == "net.minecraft")
			continue;
		if (file->fileId == "org.lwjgl")
			continue;
		// do not load what we already loaded in the first pass
		if (userOrder.contains(file->fileId))
			continue;
		if (files.contains(file->order))
		{
			// FIXME: do not throw?
			throw VersionBuildError(QObject::tr("%1 has the same order as %2")
										.arg(file->fileId, files[file->order].second->fileId));
		}
		files.insert(file->order, qMakePair(info.fileName(), file));
	}
	for (auto order : files.keys())
	{
		auto &filePair = files[order];
		m_version->VersionPatches.append(filePair.second);
	}
}
void BSClient::replySeriesGenresFinished()
{
    qDebug() << "BSClient::replySeriesGenresFinished()";

    QByteArray byteArray = m_reply->readAll();

    if(isCaptcha(byteArray))
    {
        loadSeriesGenres();
        return;
    }

    QJsonDocument document = QJsonDocument::fromJson(byteArray);

    if(!document.isObject())
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x0007"));
        return;
    }

    QHash<QString, QList<QPair<int, QString> > > seriesCategories;

    QJsonObject object = document.object();

    for(QJsonObject::const_iterator iter = object.constBegin();
            iter != object.constEnd();
            iter++)
    {
        if(!iter.value().isObject())
        {
            qDebug() << iter.value();
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0008"));
            return;
        }

        QJsonObject object_ = iter.value().toObject();

        if(!object_.contains("series"))
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0009"));
            return;
        }

        QJsonValue value = object_.value("series");

        if(!value.isArray())
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x000A"));
            return;
        }

        QList<QPair<int, QString> > series;

        QJsonArray array = iter.value().toArray();

        Q_FOREACH(const QJsonValue &value_, value.toArray())
        {
             if(!value_.isObject())
             {
                 Q_EMIT error(tr("JSON-Parse-Fehler: 0x000B"));
                 return;
             }

             QJsonObject object__ = value_.toObject();

             if(!object__.contains("name"))
             {
                 Q_EMIT error(tr("JSON-Parse-Fehler: 0x000C"));
                 return;
             }

             QJsonValue idValue = object__.value("id");

             if(!idValue.isDouble())
             {
                 Q_EMIT error(tr("JSON-Parse-Fehler: 0x000D"));
                 return;
             }

             QJsonValue nameValue = object__.value("name");

             if(!nameValue.isString())
             {
                 Q_EMIT error(tr("JSON-Parse-Fehler: 0x000E"));
                 return;
             }

             series << qMakePair(idValue.toInt(), nameValue.toString());
        }

        seriesCategories.insert(iter.key(), series);
    }

    Q_EMIT loadSeriesGenresFinished(seriesCategories);
}
void BSClient::replyEpisodesFinished()
{
    qDebug() << "BSClient::replyEpisodesFinished()";

    QByteArray byteArray = m_reply->readAll();

    if(isCaptcha(byteArray))
    {
        loadEpisodes(m_seasonId);
        return;
    }

    QJsonDocument document = QJsonDocument::fromJson(byteArray);

    if(!document.isObject())
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x0015"));
        return;
    }

    QJsonObject object = document.object();

    if(!object.contains("series"))
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x0016"));
        return;
    }

    QJsonValue value = object.value("epi");

    if(!value.isArray())
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x0017"));
        return;
    }

    QList<QPair<QString, QString> > episodes;

    Q_FOREACH(const QJsonValue &value_, value.toArray())
    {
        if(!value_.isObject())
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0018"));
            return;
        }

        QJsonObject object_ = value_.toObject();

        if(!object_.contains("german"))
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0019"));
            return;
        }

        QJsonValue germanValue = object_.value("german");

        if(!germanValue.isString())
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0020"));
            return;
        }

        QString german = germanValue.toString();

        if(!object_.contains("english"))
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0021"));
            return;
        }

        QJsonValue englishValue = object_.value("english");

        if(!englishValue.isString())
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0022"));
            return;
        }

        QString english = englishValue.toString();

        if(!object_.contains("epi"))
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0023"));
            return;
        }

        QJsonValue epiValue = object_.value("epi");

        if(!epiValue.isString())
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0024"));
            return;
        }

        QString epi = epiValue.toString();

        QString name = german;
        if(name.isEmpty())
            name = english;
        if(name.isEmpty())
            name = tr("Kein Name");

        episodes << qMakePair(QString("%0/%1").arg(m_seasonId).arg(epi), QString("%0. Folge %1").arg(epi).arg(name));
    }

    Q_EMIT loadEpisodesFinished(episodes);
}
void TWebSocketWorker::execute(int opcode, const QByteArray &payload)
{
    bool sendTask = false;
    QString es = TUrlRoute::splitPath(_requestPath).value(0).toLower() + "endpoint";
    TDispatcher<TWebSocketEndpoint> dispatcher(es);
    TWebSocketEndpoint *endpoint = dispatcher.object();

    if (!endpoint) {
        return;
    }

    try {
        tSystemDebug("Found endpoint: %s", qPrintable(es));
        tSystemDebug("TWebSocketWorker opcode: %d", opcode);

        endpoint->sessionStore = _socket->session(); // Sets websocket session
        endpoint->uuid = _socket->socketUuid();
        // Database Transaction
        setTransactionEnabled(endpoint->transactionEnabled());

        switch (_mode) {
        case Opening: {
            bool res = endpoint->onOpen(_httpSession);
            if (res) {
                // For switch response
                endpoint->taskList.prepend(qMakePair((int)TWebSocketEndpoint::OpenSuccess, QVariant()));

                if (endpoint->keepAliveInterval() > 0) {
                    endpoint->startKeepAlive(endpoint->keepAliveInterval());
                }
            } else {
                endpoint->taskList.prepend(qMakePair((int)TWebSocketEndpoint::OpenError, QVariant()));
            }
            break; }

        case Closing:
            if (!_socket->closing.exchange(true)) {
                endpoint->onClose(Tf::GoingAway);
                endpoint->unsubscribeFromAll();
            }
            break;

        case Receiving: {

            switch (opcode) {
            case TWebSocketFrame::TextFrame:
                endpoint->onTextReceived(QString::fromUtf8(payload));
                break;

            case TWebSocketFrame::BinaryFrame:
                endpoint->onBinaryReceived(payload);
                break;

            case TWebSocketFrame::Close: {
                quint16 closeCode = Tf::GoingAway;
                if (payload.length() >= 2) {
                    QDataStream ds(payload);
                    ds.setByteOrder(QDataStream::BigEndian);
                    ds >> closeCode;
                }

                if (!_socket->closing.exchange(true)) {
                    endpoint->onClose(closeCode);
                    endpoint->unsubscribeFromAll();
                }
                endpoint->close(closeCode);  // close response or disconnect
                break; }

            case TWebSocketFrame::Ping:
                endpoint->onPing(payload);
                break;

            case TWebSocketFrame::Pong:
                endpoint->onPong(payload);
                break;

            default:
                tSystemWarn("Invalid opcode: 0x%x  [%s:%d]", (int)opcode, __FILE__, __LINE__);
                break;
            }
            break; }

        default:
            break;
        }

        // Sets session to the websocket
        _socket->setSession(endpoint->session());

        for (auto &p : endpoint->taskList) {
            const QVariant &taskData = p.second;

            switch (p.first) {
            case TWebSocketEndpoint::OpenSuccess:
                _socket->sendHandshakeResponse();
                break;

            case TWebSocketEndpoint::OpenError:
                _socket->closing = true;
                _socket->closeSent = true;
                _socket->disconnect();
                goto open_error;
                break;

            case TWebSocketEndpoint::SendText:
                _socket->sendText(taskData.toString());
                sendTask = true;
                break;

            case TWebSocketEndpoint::SendBinary:
                _socket->sendBinary(taskData.toByteArray());
                sendTask = true;
                break;

            case TWebSocketEndpoint::SendClose:
                if (_socket->closing.load() && _socket->closeSent.load()) {
                    // close-frame sent and received
                    _socket->disconnect();
                } else {
                    uint closeCode = taskData.toUInt();
                    _socket->sendClose(closeCode);
                    sendTask = true;
                }
                break;

            case TWebSocketEndpoint::SendPing:
                _socket->sendPing(taskData.toByteArray());
                sendTask = true;
                break;

            case TWebSocketEndpoint::SendPong:
                _socket->sendPong(taskData.toByteArray());
                sendTask = true;
                break;

            case TWebSocketEndpoint::SendTextTo: {
                QVariantList lst = taskData.toList();
                TAbstractWebSocket *websocket = _socket->searchPeerSocket(lst[0].toByteArray());
                if (websocket) {
                    websocket->sendText(lst[1].toString());
                }
                break; }

            case TWebSocketEndpoint::SendBinaryTo: {
                QVariantList lst = taskData.toList();
                TAbstractWebSocket *websocket = _socket->searchPeerSocket(lst[0].toByteArray());
                if (websocket) {
                    websocket->sendBinary(lst[1].toByteArray());
                }
                break; }

            case TWebSocketEndpoint::SendCloseTo: {
                QVariantList lst = taskData.toList();
                TAbstractWebSocket *websocket = _socket->searchPeerSocket(lst[0].toByteArray());
                if (websocket) {
                    websocket->sendClose(lst[1].toInt());
                }
                break; }

            case TWebSocketEndpoint::Subscribe: {
                QVariantList lst = taskData.toList();
                TPublisher::instance()->subscribe(lst[0].toString(), lst[1].toBool(), _socket);
                break; }

            case TWebSocketEndpoint::Unsubscribe:
                TPublisher::instance()->unsubscribe(taskData.toString(), _socket);
                break;

            case TWebSocketEndpoint::UnsubscribeFromAll:
                TPublisher::instance()->unsubscribeFromAll(_socket);
                break;

            case TWebSocketEndpoint::PublishText: {
                QVariantList lst = taskData.toList();
                TPublisher::instance()->publish(lst[0].toString(), lst[1].toString(), _socket);
                break; }

            case TWebSocketEndpoint::PublishBinary: {
                QVariantList lst = taskData.toList();
                TPublisher::instance()->publish(lst[0].toString(), lst[1].toByteArray(), _socket);
                break; }

            case TWebSocketEndpoint::StartKeepAlive:
                _socket->startKeepAlive(taskData.toInt());
                break;

            case TWebSocketEndpoint::StopKeepAlive:
                _socket->stopKeepAlive();
                break;

            default:
                tSystemError("Invalid logic  [%s:%d]",  __FILE__, __LINE__);
                break;
            }
        }

        if (!sendTask) {
            // Receiving but not sending, so renew keep-alive
            _socket->renewKeepAlive();
        }

    open_error:
        // transaction
        if (Q_UNLIKELY(endpoint->rollbackRequested())) {
            rollbackTransactions();
        } else {
            // Commits a transaction to the database
            commitTransactions();
        }

    } catch (ClientErrorException &e) {
int PaymentechProcessor::buildCommon(QString & pordernum, const int pccardid, const int pcvv, const double pamount, const int /*pcurrid*/, QString &prequest, QString pordertype, const QString & pAuthcode, const QString & pRespdate)
{
  XSqlQuery anq;
  anq.prepare(
    "SELECT ccard_active,"
    "  formatbytea(decrypt(setbytea(ccard_number),   setbytea(:key),'bf')) AS ccard_number,"
    "  formatccnumber(decrypt(setbytea(ccard_number),setbytea(:key),'bf')) AS ccard_number_x,"
    "  formatbytea(decrypt(setbytea(ccard_name),     setbytea(:key),'bf')) AS ccard_name,"
    "  formatbytea(decrypt(setbytea(ccard_address1), setbytea(:key),'bf')) AS ccard_address1,"
    "  formatbytea(decrypt(setbytea(ccard_address2), setbytea(:key),'bf')) AS ccard_address2,"
    "  formatbytea(decrypt(setbytea(ccard_city),     setbytea(:key),'bf')) AS ccard_city,"
    "  formatbytea(decrypt(setbytea(ccard_state),    setbytea(:key),'bf')) AS ccard_state,"
    "  formatbytea(decrypt(setbytea(ccard_zip),      setbytea(:key),'bf')) AS ccard_zip,"
    "  formatbytea(decrypt(setbytea(ccard_country),  setbytea(:key),'bf')) AS ccard_country,"
    "  formatbytea(decrypt(setbytea(ccard_month_expired),setbytea(:key),'bf')) AS ccard_month_expired,"
    "  formatbytea(decrypt(setbytea(ccard_year_expired),setbytea(:key), 'bf')) AS ccard_year_expired,"
    "  ccard_type,"
    "  custinfo.* "
    "  FROM ccard, custinfo "
    "WHERE ((ccard_id=:ccardid)"
    "  AND  (ccard_cust_id=cust_id));");
  anq.bindValue(":ccardid", pccardid);
  anq.bindValue(":key",     omfgThis->_key);
  anq.exec();

  if (anq.first())
  {
    if (!anq.value("ccard_active").toBool())
    {
      _errorMsg = errorMsg(-10);
      return -10;
    }
  }
  else if (anq.lastError().type() != QSqlError::NoError)
  {
    _errorMsg = anq.lastError().databaseText();
    return -1;
  }
  else
  {
    _errorMsg = errorMsg(-17).arg(pccardid);
    return -17;
  }

  _extraHeaders.clear();
  _extraHeaders.append(qMakePair(QString("Stateless-Transaction"), QString("true")));
  _extraHeaders.append(qMakePair(QString("Auth-MID"), QString(_metricsenc->value("CCPTDivisionNumber").rightJustified(10, '0', true))));
  _extraHeaders.append(qMakePair(QString("Auth-User"), QString(_metricsenc->value("CCLogin"))));
  _extraHeaders.append(qMakePair(QString("Auth-Password"), QString(_metricsenc->value("CCPassword"))));
  _extraHeaders.append(qMakePair(QString("Content-type"), QString("SALEM05210/SLM")));

  prequest = "P74V";
  prequest += pordernum.leftJustified(22, ' ', true);

  QString ccardType = anq.value("ccard_type").toString();
  if("V" == ccardType) // Visa
    ccardType = "VI";
  else if("M" == ccardType) // Master Card
    ccardType = "MC";
  else if("A" == ccardType) // American Express
    ccardType = "AX";
  else if("D" == ccardType) // Discover
    ccardType = "DI";
  else if("P" == ccardType) // PayPal
    ccardType = "PY";
  else
  {
    _errorMsg = errorMsg(-209);
    return -209;
  }
  prequest += ccardType;

  prequest += anq.value("ccard_number").toString().leftJustified(19, ' ', true);

  QString work_month;
  work_month.setNum(anq.value("ccard_month_expired").toDouble());
  if (work_month.length() == 1)
    work_month = "0" + work_month;
  prequest += work_month + anq.value("ccard_year_expired").toString().right(2);

  prequest += _metricsenc->value("CCPTDivisionNumber").rightJustified(10, '0', true);

  double shiftedAmt = pamount * 100.0;
  int amount = (int)shiftedAmt;
  prequest += QString::number(amount).rightJustified(12, '0', true);

  // TODO: this needs to be changed to support non-us
  prequest += "840"; // CurrencyCode: U.S. Dollars

  prequest += "7"; // TransactionType: 1 - single trans over mail/phone card holder not present, 7 - e-commerce

  prequest += "    "; // EncryptionFlag, PaymentIndicator: both optional not using

  prequest += pordertype; // ActionCode 2 digit

  prequest += " "; // Reserved

  if(pordertype == "AU")
  {
    // Bill To Address Information
    prequest += "AB";
    prequest += "               "; // TelephoneType, TelephoneNumber (1,14, Optional)
    QStringList nameParts = anq.value("ccard_name").toString().split(QRegExp("\\s+"));
    QString name = "";
    if(!nameParts.isEmpty())
    {
      QString lName = nameParts.takeLast();
      QString fName = nameParts.join(" ");
      name = fName + " *" + lName;
    }
    prequest += name.leftJustified(30, ' ', true);
    prequest += anq.value("ccard_address1").toString().leftJustified(30, ' ', true);
    prequest += anq.value("ccard_address2").toString().leftJustified(28, ' ', true);

    QString cntry = anq.value("ccard_country").toString();
    XSqlQuery qCntry;
    qCntry.prepare("SELECT 1 AS ord, country_abbr FROM country WHERE country_name = :cname"
                   " UNION "
                   "SELECT 2 AS ord, country_abbr FROM country WHERE country_abbr = :cname"
                   " ORDER BY ord LIMIT 1;");
    qCntry.bindValue(":cname", cntry);
    qCntry.exec();
    if(qCntry.first())
      cntry = qCntry.value("country_abbr").toString();
    else
      cntry = "";
    prequest += cntry.leftJustified(2, ' ', true);
  
    prequest += anq.value("ccard_city").toString().leftJustified(20, ' ', true);
  
    QString state = anq.value("ccard_state").toString();
    XSqlQuery qState;
    qState.prepare("SELECT 1 AS ord, state_abbr FROM state WHERE state_name = :cname"
                   " UNION "
                   "SELECT 2 AS ord, state_abbr FROM state WHERE state_abbr = :cname"
                   " ORDER BY ord LIMIT 1;");
    qState.bindValue(":cname", state);
    qState.exec();
    if(qState.first())
      state = qState.value("state_abbr").toString();
    else
      state = "";
    prequest += state.leftJustified(2, ' ', true);
  
    prequest += anq.value("ccard_zip").toString().leftJustified(10, ' ', true);

  } // end Address Billing record

  if(pordertype == "AR")
  {
    prequest += "PA";
    prequest += pRespdate.leftJustified(6, '0', true);
    prequest += pAuthcode.leftJustified(6, ' ', true);
    prequest += "        "; // DebitTraceNumber: leave blank
  }

  if (pcvv > 0)
  {
    prequest += "FR";
    prequest += "1";
    prequest += QString::number(pcvv).leftJustified(4, ' ', true);
  }

  // version records -- should always include
  prequest += "VVISAN\r"; // add version record to end
  prequest = prequest.toUpper();

  _extraHeaders.append(qMakePair(QString("Content-Length"), QString("%1").arg(prequest.size())));

  if (DEBUG)
    qDebug("Paymentech:buildCommon built %s\n", prequest.toAscii().data());
  return 0;
}
void QSparqlQueryModelPrivate::findRoleNames()
{
    QString queryString = query.preparedQueryText().simplified();
    roleNames.clear();
    QList<QString> uniqueNames;

    bool processLoop = true;
    bool process = false;
    int firstPosition = 0;
    int deletePosition = 0;

    QChar closeChar;
    QChar openChar;
    QList<QPair<QLatin1Char, QLatin1Char> > bracketMatch;

    bracketMatch.append( qMakePair( QLatin1Char('('), QLatin1Char(')') ) );
    bracketMatch.append( qMakePair( QLatin1Char('{'), QLatin1Char('}') ) );
    bracketMatch.append( qMakePair( QLatin1Char('"'), QLatin1Char('"') ) );
    bracketMatch.append( qMakePair( QLatin1Char('\''), QLatin1Char('\'') ) );

    // check query is valid, will ensure we don't get stuck in the loop
    if ( queryString.count(QLatin1Char('(')) == queryString.count(QLatin1Char(')'))
        && queryString.count(QLatin1Char('{')) == queryString.count(QLatin1Char('}'))
        && queryString.count(QLatin1Char('"')) % 2 == 0
        && queryString.count(QLatin1Char('\'')) % 2 == 0 )
    {
        // first remove any, potentially nested, brackets
        while (processLoop) {
            if (!process) {
                for (int i = 0; i < bracketMatch.size(); ++i) {
                    firstPosition = queryString.indexOf( bracketMatch.at(i).first );
                    if (firstPosition != -1) {
                        openChar = bracketMatch.at(i).first;
                        closeChar = bracketMatch.at(i).second;
                        deletePosition = firstPosition;
                        break;
                    }
                 }
            }
            if (firstPosition != -1) {
                process = true;
                int openCount = 0;
                int closeCount = 0;
                // go to the first close, count how many opens, repeat until they match
                // then delete!
                do {
                    deletePosition = queryString.indexOf(closeChar, deletePosition+1);
                    openCount = queryString.left(deletePosition).count(openChar);
                    if(deletePosition != -1)
                        closeCount++;
                    } while (closeCount != openCount);
                    queryString.remove(firstPosition, (deletePosition-firstPosition)+1);
                    firstPosition = 0;
                    closeCount = 0;
                    process = false;
            } else {
                processLoop = false;
            }
        }

        QStringList stringList = queryString.split(QLatin1Char(' '));
        Q_FOREACH(QString word, stringList) {
            if ((word.at(0) == QLatin1Char('?') || word.at(0) == QLatin1Char('$'))
            && (!word.contains(QLatin1Char(';')) && !word.contains(QLatin1Char(':')))) {
                //remove the ? or $
                word.remove(0,1);
                // select ?u{?u a ... is valid, need to make sure
                // this is dealt with
                if (word.contains(QLatin1Char('{'))) {
                   word = word.split(QLatin1Char('{')).at(0);
                }
                QRegExp cleanUp(QLatin1String("[,]|[{]|[}]|[.]"));
                word.replace(cleanUp,QLatin1String(""));
                if (!uniqueNames.contains(word)) {
                   uniqueNames.append(word);
                }
            }
        }

        int roleCounter = Qt::UserRole + 1;
        Q_FOREACH(QString word, uniqueNames) {
            roleNames[roleCounter++] = word.toLatin1();
        }
        q->setRoleNames(roleNames);
    } else {
Exemple #7
0
EnumScriptClass::EnumScriptClass(QScriptEngine* engine, ScriptHandlerInfo* handlerInfo)
    : PrimitiveScriptClass(engine, handlerInfo)
{
    s_values = engine->toStringHandle(ParserStrings::PROPERTY_ENUM_VALUES);
    mIterableProperties.append(qMakePair(s_values, QScriptValue::PropertyFlags(QScriptValue::Undeletable)));
}
Exemple #8
0
KitInformation::ItemList ToolChainKitInformation::toUserOutput(Kit *k) const
{
    ToolChain *tc = toolChain(k);
    return ItemList() << qMakePair(tr("Compiler"), tc ? tc->displayName() : tr("None"));
}
Exemple #9
0
KitInformation::ItemList SysRootKitInformation::toUserOutput(Kit *k) const
{
    return ItemList() << qMakePair(tr("Sys Root"), sysRoot(k).toUserOutput());
}
QVariant QPdfPrintEngine::property(PrintEnginePropertyKey key) const
{
    Q_D(const QPdfPrintEngine);

    QVariant ret;
    switch (int(key)) {

    // The following keys are settings that are unsupported by the PDF PrintEngine
    // Return sensible default values to ensure consistent behavior across platforms
    case PPK_CustomBase:
        // Special case, leave null
        break;

    // The following keys are properties and settings that are supported by the PDF PrintEngine
    case PPK_CollateCopies:
        ret = d->collate;
        break;
    case PPK_ColorMode:
        ret = d->grayscale ? QPrinter::GrayScale : QPrinter::Color;
        break;
    case PPK_Creator:
        ret = d->creator;
        break;
    case PPK_DocumentName:
        ret = d->title;
        break;
    case PPK_FullPage:
        ret = d->m_pageLayout.mode() == QPageLayout::FullPageMode;
        break;
    case PPK_CopyCount:
        ret = d->copies;
        break;
    case PPK_SupportsMultipleCopies:
        ret = false;
        break;
    case PPK_NumberOfCopies:
        ret = d->copies;
        break;
    case PPK_Orientation:
        ret = d->m_pageLayout.orientation();
        break;
    case PPK_OutputFileName:
        ret = d->outputFileName;
        break;
    case PPK_PageOrder:
        ret = d->pageOrder;
        break;
    case PPK_PageSize:
        ret = d->m_pageLayout.pageSize().id();
        break;
    case PPK_PaperName:
        ret = d->m_pageLayout.pageSize().name();
        break;
    case PPK_WindowsPageSize:
        ret = d->m_pageLayout.pageSize().windowsId();
        break;
    case PPK_PaperSource:
        ret = d->paperSource;
        break;
    case PPK_PrinterName:
        ret = d->printerName;
        break;
    case PPK_PrinterProgram:
        ret = d->printProgram;
        break;
    case PPK_Resolution:
        ret = d->resolution;
        break;
    case PPK_SupportedResolutions:
        ret = QList<QVariant>() << 72;
        break;
    case PPK_PaperRect:
        ret = d->m_pageLayout.fullRectPixels(d->resolution);
        break;
    case PPK_PageRect:
        ret = d->m_pageLayout.paintRectPixels(d->resolution);
        break;
    case PPK_SelectionOption:
        ret = d->selectionOption;
        break;
    case PPK_FontEmbedding:
        ret = d->embedFonts;
        break;
    case PPK_Duplex:
        ret = d->duplex;
        break;
    case PPK_CustomPaperSize:
        ret = d->m_pageLayout.fullRectPoints().size();
        break;
    case PPK_PageMargins: {
        QList<QVariant> list;
        QMarginsF margins = d->m_pageLayout.margins(QPageLayout::Point);
        list << margins.left() << margins.top() << margins.right() << margins.bottom();
        ret = list;
        break;
    }
    case PPK_QPageSize:
        ret.setValue(d->m_pageLayout.pageSize());
        break;
    case PPK_QPageMargins: {
        QPair<QMarginsF, QPageLayout::Unit> pair = qMakePair(d->m_pageLayout.margins(), d->m_pageLayout.units());
        ret.setValue(pair);
        break;
    }
    case PPK_QPageLayout:
        ret.setValue(d->m_pageLayout);
        break;
    // No default so that compiler will complain if new keys added and not handled in this engine
    }
    return ret;
}
Exemple #11
0
void MainWindow::openFile(const QString& fileName, int line)
{
	bool isStarted = false;

	for (int i = 0; i < fileAssociations_.size(); ++i)
	{
		QString extension = fileAssociations_[i][0];
		QString application = fileAssociations_[i][1];
		QString arguments = fileAssociations_[i][2];

		if (extension.startsWith(".") == false)
			extension = "." + extension;

		if (fileName.endsWith(extension) == true)
		{
			// find [] pairs
			QList<QPair<int, int> > optionals;

			int from = 0;
			while (true)
			{
				int open = arguments.indexOf('[', from);
				if (open == -1)
					break;
				int close = arguments.indexOf(']', open + 1);
				if (close == -1)
					break;

				optionals.push_back(qMakePair(open, close));

				from = close + 1;
			}

			if (line != -1)
			{
				while (true)
				{
					int index = arguments.indexOf("<line>");
					if (index == -1)
						break;

					// optional?
					int open = arguments.lastIndexOf('[', index);
					int close = arguments.indexOf(']', index);

					if (open == -1 || close == -1)
					{
						// not optional
						arguments.replace(index, 6, QString::number(line));
					}
					else
					{
						// optional
						arguments.remove(close, 1);
						arguments.replace(index, 6, QString::number(line));
						arguments.remove(open, 1);
					}
				}
			}
			else
			{
				while (true)
				{
					int index = arguments.indexOf("<line>");
					if (index == -1)
						break;

					// optional?
					int open = arguments.lastIndexOf('[', index);
					int close = arguments.indexOf(']', index);

					if (open == -1 || close == -1)
					{
						// not optional
						arguments.remove(index, 6);
					}
					else
					{
						// optional
						arguments.remove(open, close - open + 1);
					}
				}
			}

			QString proc = "\"" + application + "\"" + " " + "\"" + fileName + "\"";
			QString proc_arg = "\"" + application + "\"" + " " + "\"" + fileName + "\"" + " " + arguments;

#ifdef Q_OS_MAC
		if (QFileInfo(application).suffix().toLower() == "app")
		{
			QProcess::startDetached("open -a " + proc);
		}
		else
		{
			QProcess::startDetached(proc_arg);
		}
#else
		QProcess::startDetached(proc_arg);
#endif

			isStarted = true;
			break;
		}
	}

	if (isStarted == false)
		QDesktopServices::openUrl(QUrl::fromLocalFile(fileName));
}
Exemple #12
0
QFormBuilderStrings::QFormBuilderStrings() :
    buddyProperty(QLatin1String("buddy")),
    cursorProperty(QLatin1String("cursor")),
    objectNameProperty(QLatin1String("objectName")),
    trueValue(QLatin1String("true")),
    falseValue(QLatin1String("false")),
    horizontalPostFix(QLatin1String("Horizontal")),
    separator(QLatin1String("separator")),
    defaultTitle(QLatin1String("Page")),
    titleAttribute(QLatin1String("title")),
    labelAttribute(QLatin1String("label")),
    toolTipAttribute(QLatin1String("toolTip")),
    whatsThisAttribute(QLatin1String("whatsThis")),
    flagsAttribute(QLatin1String("flags")),
    iconAttribute(QLatin1String("icon")),
    pixmapAttribute(QLatin1String("pixmap")),
    textAttribute(QLatin1String("text")),
    currentIndexProperty(QLatin1String("currentIndex")),
    toolBarAreaAttribute(QLatin1String("toolBarArea")),
    toolBarBreakAttribute(QLatin1String("toolBarBreak")),
    dockWidgetAreaAttribute(QLatin1String("dockWidgetArea")),
    marginProperty(QLatin1String("margin")),
    spacingProperty(QLatin1String("spacing")),
    leftMarginProperty(QLatin1String("leftMargin")),
    topMarginProperty(QLatin1String("topMargin")),
    rightMarginProperty(QLatin1String("rightMargin")),
    bottomMarginProperty(QLatin1String("bottomMargin")),
    horizontalSpacingProperty(QLatin1String("horizontalSpacing")),
    verticalSpacingProperty(QLatin1String("verticalSpacing")),
    sizeHintProperty(QLatin1String("sizeHint")),
    sizeTypeProperty(QLatin1String("sizeType")),
    orientationProperty(QLatin1String("orientation")),
    styleSheetProperty(QLatin1String("styleSheet")),
    qtHorizontal(QLatin1String("Qt::Horizontal")),
    qtVertical(QLatin1String("Qt::Vertical")),
    currentRowProperty(QLatin1String("currentRow")),
    tabSpacingProperty(QLatin1String("tabSpacing")),
    qWidgetClass(QLatin1String("QWidget")),
    lineClass(QLatin1String("Line")),
    geometryProperty(QLatin1String("geometry")),
    scriptWidgetVariable(QLatin1String("widget")),
    scriptChildWidgetsVariable(QLatin1String("childWidgets"))
{
    itemRoles.append(qMakePair(Qt::FontRole, QString::fromLatin1("font")));
    itemRoles.append(qMakePair(Qt::TextAlignmentRole, QString::fromLatin1("textAlignment")));
    itemRoles.append(qMakePair(Qt::BackgroundRole, QString::fromLatin1("background")));
    itemRoles.append(qMakePair(Qt::ForegroundRole, QString::fromLatin1("foreground")));
    itemRoles.append(qMakePair(Qt::CheckStateRole, QString::fromLatin1("checkState")));

    foreach (const RoleNName &it, itemRoles)
        treeItemRoleHash.insert(it.second, it.first);

    itemTextRoles.append(qMakePair(qMakePair(Qt::EditRole, Qt::DisplayPropertyRole),
                                   textAttribute)); // This must be first for the loop below
    itemTextRoles.append(qMakePair(qMakePair(Qt::ToolTipRole, Qt::ToolTipPropertyRole),
                                   toolTipAttribute));
    itemTextRoles.append(qMakePair(qMakePair(Qt::StatusTipRole, Qt::StatusTipPropertyRole),
                                   QString::fromLatin1("statusTip")));
    itemTextRoles.append(qMakePair(qMakePair(Qt::WhatsThisRole, Qt::WhatsThisPropertyRole),
                                   whatsThisAttribute));

    // Note: this skips the first item!
    QList<TextRoleNName>::const_iterator it = itemTextRoles.constBegin(), end = itemTextRoles.constEnd();
    while (++it != end)
        treeItemTextRoleHash.insert(it->second, it->first);
}
Exemple #13
0
int QgsAtlasComposition::updateFeatures()
{
  //needs to be called when layer, filter, sort changes

  if ( !mCoverageLayer )
  {
    return 0;
  }

  QgsExpressionContext expressionContext = createExpressionContext();

  updateFilenameExpression();

  // select all features with all attributes
  QgsFeatureRequest req;

  QScopedPointer<QgsExpression> filterExpression;
  if ( mFilterFeatures && !mFeatureFilter.isEmpty() )
  {
    filterExpression.reset( new QgsExpression( mFeatureFilter ) );
    if ( filterExpression->hasParserError() )
    {
      mFilterParserError = filterExpression->parserErrorString();
      return 0;
    }

    //filter good to go
    req.setFilterExpression( mFeatureFilter );
  }
  mFilterParserError = QString();

  QgsFeatureIterator fit = mCoverageLayer->getFeatures( req );

  QScopedPointer<QgsExpression> nameExpression;
  if ( !mPageNameExpression.isEmpty() )
  {
    nameExpression.reset( new QgsExpression( mPageNameExpression ) );
    if ( nameExpression->hasParserError() )
    {
      nameExpression.reset( nullptr );
    }
    nameExpression->prepare( &expressionContext );
  }

  // We cannot use nextFeature() directly since the feature pointer is rewinded by the rendering process
  // We thus store the feature ids for future extraction
  QgsFeature feat;
  mFeatureIds.clear();
  mFeatureKeys.clear();
  int sortIdx = mCoverageLayer->fieldNameIndex( mSortKeyAttributeName );

  while ( fit.nextFeature( feat ) )
  {
    expressionContext.setFeature( feat );

    QString pageName;
    if ( !nameExpression.isNull() )
    {
      QVariant result = nameExpression->evaluate( &expressionContext );
      if ( nameExpression->hasEvalError() )
      {
        QgsMessageLog::logMessage( tr( "Atlas name eval error: %1" ).arg( nameExpression->evalErrorString() ), tr( "Composer" ) );
      }
      pageName = result.toString();
    }

    mFeatureIds.push_back( qMakePair( feat.id(), pageName ) );

    if ( mSortFeatures && sortIdx != -1 )
    {
      mFeatureKeys.insert( feat.id(), feat.attributes().at( sortIdx ) );
    }
  }

  // sort features, if asked for
  if ( !mFeatureKeys.isEmpty() )
  {
    FieldSorter sorter( mFeatureKeys, mSortAscending );
    qSort( mFeatureIds.begin(), mFeatureIds.end(), sorter );
  }

  emit numberFeaturesChanged( mFeatureIds.size() );

  //jump to first feature if currently using an atlas preview
  //need to do this in case filtering/layer change has altered matching features
  if ( mComposition->atlasMode() == QgsComposition::PreviewAtlas )
  {
    firstFeature();
  }

  return mFeatureIds.size();
}
 PropertySheetPixmapValue PropertySheetIconValue::pixmap(QIcon::Mode mode, QIcon::State state) const
 {
     const ModeStateKey pair = qMakePair(mode, state);
     return m_data->m_paths.value(pair);
 }
Exemple #15
0
void AbstractStructureParser::addByteArray(const QLatin1String &name, QByteArray *str)
{
	m_byteArrays.append(qMakePair(name, str));
}
void ConfigWidgetProxy::createProjectConfigPage( QString const & title, unsigned int pagenumber, QString const & icon )
{
	_projectTitleMap.insert( pagenumber, qMakePair( title, icon ) );
}
Exemple #17
0
void AbstractStructureParser::addString(const QLatin1String &name, QString *str)
{
	m_strings.append(qMakePair(name, str));
}
Exemple #18
0
double QgsComposerHtml::findNearbyPageBreak( double yPos )
{
  if ( !mWebPage || !mRenderedPage || !mUseSmartBreaks )
  {
    return yPos;
  }

  //convert yPos to pixels
  int idealPos = yPos * htmlUnitsToMM();

  //if ideal break pos is past end of page, there's nothing we need to do
  if ( idealPos >= mRenderedPage->height() )
  {
    return yPos;
  }

  int maxSearchDistance = mMaxBreakDistance * htmlUnitsToMM();

  //loop through all lines just before ideal break location, up to max distance
  //of maxSearchDistance
  int changes = 0;
  QRgb currentColor;
  bool currentPixelTransparent = false;
  bool previousPixelTransparent = false;
  QRgb pixelColor;
  QList< QPair<int, int> > candidates;
  int minRow = qMax( idealPos - maxSearchDistance, 0 );
  for ( int candidateRow = idealPos; candidateRow >= minRow; --candidateRow )
  {
    changes = 0;
    currentColor = qRgba( 0, 0, 0, 0 );
    //check all pixels in this line
    for ( int col = 0; col < mRenderedPage->width(); ++col )
    {
      //count how many times the pixels change color in this row
      //eventually, we select a row to break at with the minimum number of color changes
      //since this is likely a line break, or gap between table cells, etc
      //but very unlikely to be midway through a text line or picture
      pixelColor = mRenderedPage->pixel( col, candidateRow );
      currentPixelTransparent = qAlpha( pixelColor ) == 0;
      if ( pixelColor != currentColor && !( currentPixelTransparent && previousPixelTransparent ) )
      {
        //color has changed
        currentColor = pixelColor;
        changes++;
      }
      previousPixelTransparent = currentPixelTransparent;
    }
    candidates.append( qMakePair( candidateRow, changes ) );
  }

  //sort candidate rows by number of changes ascending, row number descending
  qSort( candidates.begin(), candidates.end(), candidateSort );
  //first candidate is now the largest row with smallest number of changes

  //ok, now take the mid point of the best candidate position
  //we do this so that the spacing between text lines is likely to be split in half
  //otherwise the html will be broken immediately above a line of text, which
  //looks a little messy
  int maxCandidateRow = candidates[0].first;
  int minCandidateRow = maxCandidateRow + 1;
  int minCandidateChanges = candidates[0].second;

  QList< QPair<int, int> >::iterator it;
  for ( it = candidates.begin(); it != candidates.end(); ++it )
  {
    if (( *it ).second != minCandidateChanges || ( *it ).first != minCandidateRow - 1 )
    {
      //no longer in a consecutive block of rows of minimum pixel color changes
      //so return the row mid-way through the block
      //first converting back to mm
      return ( minCandidateRow + ( maxCandidateRow - minCandidateRow ) / 2 ) / htmlUnitsToMM();
    }
    minCandidateRow = ( *it ).first;
  }

  //above loop didn't work for some reason
  //return first candidate converted to mm
  return candidates[0].first / htmlUnitsToMM();
}
Exemple #19
0
  void medianCut( QVector<QRgb> &colorTable, int nColors, const QImage &inputImage )
  {
    QHash<QRgb, int> inputColors;
    imageColors( inputColors, inputImage );

    if ( inputColors.size() <= nColors ) //all the colors in the image can be mapped to one palette color
    {
      colorTable.resize( inputColors.size() );
      int index = 0;
      for ( auto inputColorIt = inputColors.constBegin(); inputColorIt != inputColors.constEnd(); ++inputColorIt )
      {
        colorTable[index] = inputColorIt.key();
        ++index;
      }
      return;
    }

    //create first box
    QgsColorBox firstBox; //QList< QPair<QRgb, int> >
    int firstBoxPixelSum = 0;
    for ( auto  inputColorIt = inputColors.constBegin(); inputColorIt != inputColors.constEnd(); ++inputColorIt )
    {
      firstBox.push_back( qMakePair( inputColorIt.key(), inputColorIt.value() ) );
      firstBoxPixelSum += inputColorIt.value();
    }

    QgsColorBoxMap colorBoxMap; //QMultiMap< int, ColorBox >
    colorBoxMap.insert( firstBoxPixelSum, firstBox );
    QMap<int, QgsColorBox>::iterator colorBoxMapIt = colorBoxMap.end();

    //split boxes until number of boxes == nColors or all the boxes have color count 1
    bool allColorsMapped = false;
    while ( colorBoxMap.size() < nColors )
    {
      //start at the end of colorBoxMap and pick the first entry with number of colors < 1
      colorBoxMapIt = colorBoxMap.end();
      while ( true )
      {
        --colorBoxMapIt;
        if ( colorBoxMapIt.value().size() > 1 )
        {
          splitColorBox( colorBoxMapIt.value(), colorBoxMap, colorBoxMapIt );
          break;
        }
        if ( colorBoxMapIt == colorBoxMap.begin() )
        {
          allColorsMapped = true;
          break;
        }
      }

      if ( allColorsMapped )
      {
        break;
      }
    }

    //get representative colors for the boxes
    int index = 0;
    colorTable.resize( colorBoxMap.size() );
    for ( auto colorBoxIt = colorBoxMap.constBegin(); colorBoxIt != colorBoxMap.constEnd(); ++colorBoxIt )
    {
      colorTable[index] = boxColor( colorBoxIt.value(), colorBoxIt.key() );
      ++index;
    }
  }
Exemple #20
0
// ### move this to qnetworkcookie_p.h and share with qnetworkaccesshttpbackend
static QPair<QByteArray, QByteArray> nextField(const QByteArray &text, int &position)
{
    // format is one of:
    //    (1)  token
    //    (2)  token = token
    //    (3)  token = quoted-string
    int i;
    const int length = text.length();
    position = nextNonWhitespace(text, position);

    // parse the first part, before the equal sign
    for (i = position; i < length; ++i) {
        register char c = text.at(i);
        if (c == ';' || c == ',' || c == '=')
            break;
    }

    QByteArray first = text.mid(position, i - position).trimmed();
    position = i;

    if (first.isEmpty())
        return qMakePair(QByteArray(), QByteArray());
    if (i == length || text.at(i) != '=')
        // no equal sign, we found format (1)
        return qMakePair(first, QByteArray());

    QByteArray second;
    second.reserve(32);         // arbitrary but works for most cases

    i = nextNonWhitespace(text, position + 1);
    if (i < length && text.at(i) == '"') {
        // a quote, we found format (3), where:
        // quoted-string  = ( <"> *(qdtext | quoted-pair ) <"> )
        // qdtext         = <any TEXT except <">>
        // quoted-pair    = "\" CHAR
        ++i;
        while (i < length) {
            register char c = text.at(i);
            if (c == '"') {
                // end of quoted text
                break;
            } else if (c == '\\') {
                ++i;
                if (i >= length)
                    // broken line
                    return qMakePair(QByteArray(), QByteArray());
                c = text.at(i);
            }

            second += c;
            ++i;
        }

        for ( ; i < length; ++i) {
            register char c = text.at(i);
            if (c == ',' || c == ';')
                break;
        }
        position = i;
    } else {
        // no quote, we found format (2)
        position = i;
        for ( ; i < length; ++i) {
            register char c = text.at(i);
            if (c == ',' || c == ';' || isLWS(c))
                break;
        }

        second = text.mid(position, i - position).trimmed();
        position = i;
    }

    if (second.isNull())
        second.resize(0); // turns into empty-but-not-null
    return qMakePair(first, second);
}
void TWebSocketWorker::setPayload(TWebSocketFrame::OpCode opCode, const QByteArray &payload)
{
    _payloads << qMakePair((int)opCode, payload);
}
Exemple #22
0
#include "plansza.h"

//wersory kierunkowe
const QPair <int,int> DIR[8] = {
qMakePair(0, 1), //GORA
qMakePair(1, 0), //PRAWO
qMakePair(0, -1), //DOL
qMakePair(-1, 0), //LEWO
qMakePair(1, 1), //GORA-PRAWO SKOS
qMakePair(1, -1), //DOL-PRAWO SKOS
qMakePair(-1, -1), //DOL-LEWO SKOS
qMakePair(-1, 1), //GORA-LEWO SKOS
};


Plansza::Plansza()
{
	for ( int i = 0; i < rozmiarDruzyny; i++ )
	{
		dane[i] = i;
		dane[i + rozmiarDruzyny] = i + 42;
	}

	dane[ 14 ] = 3; 	//pilka 0 na pozycje 3
	dane[ 15 ] = 45;	//pilka 1 na pozycje 45

	dane[16] = 0; //zaczyna gracz 0
}


bool Plansza::czyPilka( int pionekId )
namespace Actions
{
ActionTools::StringListPair WebDownloadInstance::destinations = qMakePair(
            QStringList() << "variable" << "file",
            QStringList() << QT_TRANSLATE_NOOP("WebDownloadInstance::destinations", "Variable")
            << QT_TRANSLATE_NOOP("WebDownloadInstance::destinations", "File"));

WebDownloadInstance::WebDownloadInstance(const ActionTools::ActionDefinition *definition, QObject *parent)
    : ActionTools::ActionInstance(definition, parent),
      mNetworkAccessManager(new QNetworkAccessManager(this)),
      mReply(0),
      mDestination(Variable),
      mProgressDialog(new QProgressDialog)
{
    connect(mProgressDialog, SIGNAL(canceled()), this, SLOT(canceled()));
}

WebDownloadInstance::~WebDownloadInstance()
{
    delete mProgressDialog;
}

void WebDownloadInstance::startExecution()
{
    bool ok = true;

    QString urlString = evaluateString(ok, "url");
    mDestination = evaluateListElement<Destination>(ok, destinations, "destination");
    mVariable = evaluateVariable(ok, "variable");
    QString file = evaluateString(ok, "file");


    if(!ok)
        return;

    QUrl url(urlString);
    if(url.scheme() == QString())
        url = QUrl("http://" + urlString, QUrl::TolerantMode);

    if(!url.isValid())
    {
        setCurrentParameter("url");
        emit executionException(ActionTools::ActionException::BadParameterException, tr("Invalid URL"));
        return;
    }

    if(mDestination == File)
    {
        mFile.setFileName(file);
        if(!mFile.open(QIODevice::WriteOnly))
        {
            setCurrentParameter("file");
            emit executionException(CannotOpenFileException, tr("Cannot write to file"));
            return;
        }
    }

    mReply = mNetworkAccessManager->get(QNetworkRequest(url));

    connect(mReply, SIGNAL(finished()), this, SLOT(finished()));
    connect(mReply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloadProgress(qint64,qint64)));
    connect(mReply, SIGNAL(readyRead()), this, SLOT(readyRead()));

    mProgressDialog->setModal(false);
    mProgressDialog->setWindowTitle(tr("Downloading"));
    mProgressDialog->setLabelText(tr("Downloading..."));
    mProgressDialog->setMaximum(100);
    mProgressDialog->show();
}

void WebDownloadInstance::stopExecution()
{
    if(mReply)
        mReply->abort();
}

void WebDownloadInstance::finished()
{
    mFile.close();

    switch(mReply->error())
    {
    case QNetworkReply::NoError:
        if(mDestination == Variable)
            setVariable(mVariable, QString::fromUtf8(mReply->readAll()));

        emit executionEnded();
        break;
    case QNetworkReply::OperationCanceledError:
        if(mDestination == File)
            mFile.remove();

        emit executionEnded();
        break;
    default:
    {
        if(mDestination == File)
            mFile.remove();

        setCurrentParameter("url");

        emit executionException(DownloadException, tr("Download error: %1").arg(mReply->errorString()));
    }
    break;
    }

    mProgressDialog->close();

    mReply->deleteLater();
    mReply = 0;
}

void WebDownloadInstance::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    if(bytesTotal > 0)
        mProgressDialog->setValue((bytesReceived * 100) / bytesTotal);
}

void WebDownloadInstance::readyRead()
{
    if(mDestination == File)
        mFile.write(mReply->readAll());
}

void WebDownloadInstance::canceled()
{
    if(mReply)
        mReply->abort();
}
}
Exemple #24
0
QgsNamedColorList QgsCustomColorScheme::fetchColors( const QString &context, const QColor &baseColor )
{
  Q_UNUSED( context );
  Q_UNUSED( baseColor );

  //fetch predefined custom colors
  QgsNamedColorList colorList;
  QgsSettings settings;

  //check if settings contains custom palette
  if ( !settings.contains( QStringLiteral( "/colors/palettecolors" ) ) )
  {
    //no custom palette, return default colors
    colorList.append( qMakePair( QColor( 0, 0, 0 ), QString() ) );
    colorList.append( qMakePair( QColor( 255, 255, 255 ), QString() ) );
    colorList.append( qMakePair( QColor( 166, 206, 227 ), QString() ) );
    colorList.append( qMakePair( QColor( 31, 120, 180 ), QString() ) );
    colorList.append( qMakePair( QColor( 178, 223, 138 ), QString() ) );
    colorList.append( qMakePair( QColor( 51, 160, 44 ), QString() ) );
    colorList.append( qMakePair( QColor( 251, 154, 153 ), QString() ) );
    colorList.append( qMakePair( QColor( 227, 26, 28 ), QString() ) );
    colorList.append( qMakePair( QColor( 253, 191, 111 ), QString() ) );
    colorList.append( qMakePair( QColor( 255, 127, 0 ), QString() ) );

    return colorList;
  }

  QList< QVariant > customColorVariants = settings.value( QStringLiteral( "colors/palettecolors" ) ).toList();
  QList< QVariant > customColorLabels = settings.value( QStringLiteral( "colors/palettelabels" ) ).toList();

  //generate list from custom colors
  int colorIndex = 0;
  for ( QList< QVariant >::iterator it = customColorVariants.begin();
        it != customColorVariants.end(); ++it )
  {
    QColor color = ( *it ).value<QColor>();
    QString label;
    if ( customColorLabels.length() > colorIndex )
    {
      label = customColorLabels.at( colorIndex ).toString();
    }

    colorList.append( qMakePair( color, label ) );
    colorIndex++;
  }

  return colorList;
}
void BSClient::replySeriesFinished()
{
    qDebug() << "BSClient::replySeriesFinished()";

    QByteArray byteArray = m_reply->readAll();

    if(isCaptcha(byteArray))
    {
        loadSeries();
        return;
    }

    QJsonDocument document = QJsonDocument::fromJson(byteArray);

    if(!document.isArray())
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x0001"));
        return;
    }

    QList<QPair<QString, QString> > series;

    QJsonArray array = document.array();

    Q_FOREACH(const QJsonValue &value, array)
    {
        if(!value.isObject())
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0002"));
            return;
        }

        QJsonObject object = value.toObject();

        if(!object.contains("id"))
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0003"));
            return;
        }

        QJsonValue idValue = object.value("id");

        if(!idValue.isString())
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0004"));
            return;
        }

        if(!object.contains("series"))
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0005"));
            return;
        }

        QJsonValue seriesValue = object.value("series");

        if(!seriesValue.isString())
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0006"));
            return;
        }

        series << qMakePair(idValue.toString(), seriesValue.toString());
    }

    Q_EMIT loadSeriesFinished(series);
}
Exemple #26
0
void ExportBuiltin::fillTargetReplacements(ExportContext *ctx)
{
    QStringList wildcards1;
    wildcards1 <<
        "*.pch" <<
        "*.plist" <<
        "*.pbxproj" <<
        "*.java" <<
        "*.xml" <<
        "*.appxmanifest" <<
        "*.gradle" <<
        "*.html" <<
        "*.project";
    ctx->wildcards << wildcards1;

    QList<QPair<QByteArray, QByteArray> > replaceList1;
    if (!ctx->templatename.isEmpty())
    {
    	replaceList1 << qMakePair(ctx->templatename.toUtf8(), ctx->base.toUtf8());
    	replaceList1 << qMakePair(ctx->templatenamews.toLatin1(), ctx->basews.toLatin1());
    }
    if (ctx->deviceFamily == e_Android){
        replaceList1 << qMakePair(QString("com.giderosmobile.androidtemplate").toUtf8(), ctx->args["package"].toUtf8());
        replaceList1 << qMakePair(QString("android:versionCode=\"1\"").toUtf8(), ("android:versionCode=\""+QString::number(ctx->properties.version_code)+"\"").toUtf8());
        replaceList1 << qMakePair(QString("android:versionName=\"1.0\"").toUtf8(), ("android:versionName=\""+ctx->properties.version+"\"").toUtf8());
        QString orientation = "android:screenOrientation=\"portrait\"";
        switch(ctx->properties.orientation){
            case 0:
                if(ctx->properties.autorotation > 0)
                    orientation = "android:screenOrientation=\"sensorPortrait\"";
                else
                    orientation = "android:screenOrientation=\"portrait\"";
                break;
            case 1:
                if(ctx->properties.autorotation > 0)
                    orientation = "android:screenOrientation=\"sensorLandscape\"";
                else
                    orientation = "android:screenOrientation=\"landscape\"";
                break;
            case 2:
                if(ctx->properties.autorotation > 0)
                    orientation = "android:screenOrientation=\"sensorPortrait\"";
                else
                    orientation = "android:screenOrientation=\"reversePortrait\"";
                break;
            case 3:
                if(ctx->properties.autorotation > 0)
                    orientation = "android:screenOrientation=\"sensorLandscape\"";
                else
                    orientation = "android:screenOrientation=\"reverseLandscape\"";
                break;
        }

        replaceList1 << qMakePair(QString("android:screenOrientation=\"portrait\"").toUtf8(), orientation.toUtf8());
    }
    else if(ctx->deviceFamily == e_MacOSXDesktop){
        QString category = "public.app-category.games";
        if(ctx->args.contains("category"))
            category = ctx->args["category"];
        if(ctx->args.contains("bundle"))
            replaceList1 << qMakePair(QString("com.yourcompany."+ctx->base).toUtf8(), ctx->args["bundle"].toUtf8());
        replaceList1 << qMakePair(QString("<key>NOTE</key>").toUtf8(), ("<key>LSApplicationCategoryType</key>\n	<string>"+category.toUtf8()+"</string>\n	<key>CFBundleShortVersionString</key>\n	<string>"+ctx->properties.version+"</string>\n	<key>CFBundleVersion</key>\n	<string>"+ctx->properties.version+"</string>\n	<key>CFBundleName</key>\n	<string>"+ctx->base.toUtf8()+"</string>\n	<key>NOTE</key>").toUtf8());
    }
    else if(ctx->deviceFamily == e_iOS){
        if(ctx->args.contains("bundle"))
            replaceList1 << qMakePair(QString("com.yourcompany.${PRODUCT_NAME:rfc1034identifier}").toUtf8(), ctx->args["bundle"].toUtf8());
        replaceList1 << qMakePair(QString("<string>1.0</string>").toUtf8(), ("<string>"+ctx->properties.version+"</string>").toUtf8());
    }
    else if(ctx->deviceFamily == e_WinRT){
        replaceList1 << qMakePair(QString("Gideros Player").toUtf8(), ctx->base.toUtf8());
        replaceList1 << qMakePair(QString("giderosgame").toUtf8(), ctx->basews.toUtf8());
        replaceList1 << qMakePair(QString("com.giderosmobile.windowsphone").toUtf8(), ctx->args["package"].toUtf8());
        replaceList1 << qMakePair(QString("com.giderosmobile.windows").toUtf8(), ctx->args["package"].toUtf8());
        replaceList1 << qMakePair(QString("Gideros Mobile").toUtf8(), ctx->args["organization"].toUtf8());
    }
    else if(ctx->deviceFamily == e_Html5){
        replaceList1 << qMakePair(QString("<title>Gideros</title>").toUtf8(), ("<title>"+ctx->base+"</title>").toUtf8());
        replaceList1 << qMakePair(QString("gideros.GApp").toUtf8(), (ctx->base+".GApp").toUtf8());
        replaceList1 << qMakePair(QString("GIDEROS_MEMORY_MB=128").toUtf8(),QString("GIDEROS_MEMORY_MB=%1").arg(ctx->properties.html5_mem).toUtf8());
    }
    ctx->replaceList << replaceList1;
}
void BSClient::replySeasonsFinished()
{
    qDebug() << "BSClient::replySeasonsFinished()";

    QByteArray byteArray = m_reply->readAll();

    if(isCaptcha(byteArray))
    {
        loadSeasons(m_episodeId);
        return;
    }

    QJsonDocument document = QJsonDocument::fromJson(byteArray);

    if(!document.isObject())
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x000F"));
        return;
    }

    QJsonObject object = document.object();

    if(!object.contains("series"))
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x0010"));
        return;
    }

    QJsonValue value = object.value("series");

    if(!value.isObject())
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x0011"));
        return;
    }

    QJsonObject object_ = value.toObject();

    if(!object_.contains("seasons"))
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x0012"));
        return;
    }

    QJsonValue seasonsValue = object_.value("seasons");

    if(!seasonsValue.isString())
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x0013"));
        return;
    }

    QString seasonsString = seasonsValue.toString();

    bool ok;
    int seasonsCount = seasonsString.toInt(&ok);
    if(!ok)
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x0014"));
        return;
    }

    QList<QPair<QString, QString> > seasons;

    for(int i = 1; i <= seasonsCount; i++)
        seasons << qMakePair(QString("%0/%1").arg(m_seriesId).arg(i), tr("%0. Staffel").arg(i));

    Q_EMIT loadSeasonsFinished(seasons);
}
Exemple #28
0
QPair<bool, bool> UiMessageBox::getCheckboxes() {
    return qMakePair(ui->checkSmooth->isChecked(), ui->checkTrigger->isChecked());
}
void BSClient::replyLinksFinished()
{
    qDebug() << "BSClient::replyLinksFinished()";

    QByteArray byteArray = m_reply->readAll();

    if(isCaptcha(byteArray))
    {
        loadLinks(m_episodeId);
        return;
    }

    QJsonDocument document = QJsonDocument::fromJson(byteArray);

    if(!document.isObject())
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x0025"));
        return;
    }

    QJsonObject object = document.object();

    if(!object.contains("links"))
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x0026"));
        return;
    }

    QJsonValue value = object.value("links");

    if(!value.isArray())
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x0027"));
        return;
    }

    QList<QPair<QString, QString> > links;

    Q_FOREACH(const QJsonValue &value_, value.toArray())
    {
        if(!value_.isObject())
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0028"));
            return;
        }

        QJsonObject object_ = value_.toObject();

        if(!object_.contains("hoster"))
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0029"));
            return;
        }

        QJsonValue hosterValue = object_.value("hoster");

        if(!hosterValue.isString())
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x002A"));
            return;
        }

        if(!object_.contains("id"))
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x002B"));
            return;
        }

        QJsonValue idValue = object_.value("id");

        if(!hosterValue.isString())
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x002C"));
            return;
        }

        links << qMakePair(hosterValue.toString(), idValue.toString());
    }

    Q_EMIT loadLinksFinished(links);
}
void QEGLPlatformContext::updateFormatFromGL()
{
#ifndef QT_NO_OPENGL
    // Have to save & restore to prevent QOpenGLContext::currentContext() from becoming
    // inconsistent after QOpenGLContext::create().
    EGLDisplay prevDisplay = eglGetCurrentDisplay();
    if (prevDisplay == EGL_NO_DISPLAY) // when no context is current
        prevDisplay = m_eglDisplay;
    EGLContext prevContext = eglGetCurrentContext();
    EGLSurface prevSurfaceDraw = eglGetCurrentSurface(EGL_DRAW);
    EGLSurface prevSurfaceRead = eglGetCurrentSurface(EGL_READ);

    // Rely on the surfaceless extension, if available. This is beneficial since we can
    // avoid creating an extra pbuffer surface which is apparently troublesome with some
    // drivers (Mesa) when certain attributes are present (multisampling).
    EGLSurface tempSurface = EGL_NO_SURFACE;
    if (!q_hasEglExtension(m_eglDisplay, "EGL_KHR_surfaceless_context"))
        tempSurface = createTemporaryOffscreenSurface();

    if (eglMakeCurrent(m_eglDisplay, tempSurface, tempSurface, m_eglContext)) {
        if (m_format.renderableType() == QSurfaceFormat::OpenGL
            || m_format.renderableType() == QSurfaceFormat::OpenGLES) {
            const GLubyte *s = glGetString(GL_VERSION);
            if (s) {
                QByteArray version = QByteArray(reinterpret_cast<const char *>(s));
                int major, minor;
                if (QPlatformOpenGLContext::parseOpenGLVersion(version, major, minor)) {
                    m_format.setMajorVersion(major);
                    m_format.setMinorVersion(minor);
                }
            }
            m_format.setProfile(QSurfaceFormat::NoProfile);
            m_format.setOptions(QSurfaceFormat::FormatOptions());
            if (m_format.renderableType() == QSurfaceFormat::OpenGL) {
                // Check profile and options.
                if (m_format.majorVersion() < 3) {
                    m_format.setOption(QSurfaceFormat::DeprecatedFunctions);
                } else {
                    GLint value = 0;
                    glGetIntegerv(GL_CONTEXT_FLAGS, &value);
                    if (!(value & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT))
                        m_format.setOption(QSurfaceFormat::DeprecatedFunctions);
                    if (value & GL_CONTEXT_FLAG_DEBUG_BIT)
                        m_format.setOption(QSurfaceFormat::DebugContext);
                    if (m_format.version() >= qMakePair(3, 2)) {
                        value = 0;
                        glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &value);
                        if (value & GL_CONTEXT_CORE_PROFILE_BIT)
                            m_format.setProfile(QSurfaceFormat::CoreProfile);
                        else if (value & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT)
                            m_format.setProfile(QSurfaceFormat::CompatibilityProfile);
                    }
                }
            }
        }
        eglMakeCurrent(prevDisplay, prevSurfaceDraw, prevSurfaceRead, prevContext);
    } else {
        qWarning("QEGLPlatformContext: Failed to make temporary surface current, format not updated");
    }
    if (tempSurface != EGL_NO_SURFACE)
        destroyTemporaryOffscreenSurface(tempSurface);
#endif // QT_NO_OPENGL
}