Example #1
0
void QAtResult::resultToCode( const QString& value )
{
    QString val;
    int index;

    // Determine what kind of error report we have.
    if ( value.startsWith( "+CME ERROR:", Qt::CaseInsensitive ) ||
         value.startsWith( "+EXT ERROR:", Qt::CaseInsensitive ) ) {

        // Extended or GPRS error report.
        val = value.mid( 11 ).trimmed();
        index = numeric( val );
        if ( index >= 0 ) {
            d->resultCode = (QAtResult::ResultCode)index;
            d->verbose = false;
            return;
        }

    } else if ( value.startsWith( "+CMS ERROR:", Qt::CaseInsensitive ) ) {

        // Check the SMS codes before the main codes, as there is
        // some overlap in the message names.
        val = value.mid( 11 ).trimmed();
        index = numeric( val );
        if ( index >= 0 ) {
            d->resultCode = (QAtResult::ResultCode)index;
            d->verbose = false;
            return;
        }
        index = 0;
        while ( ext_codes[index].code != QAtResult::MEFailure )
            ++index;
        while ( index < num_ext_codes ) {
            if ( match( val, ext_codes[index].name ) ) {
                d->resultCode = ext_codes[index].code;
                d->verbose = true;
                return;
            }
            ++index;
        }

    } else {

        // Probably something like OK, ERROR, etc.  Scan the basic codes only.
        for ( index = 0; index < num_basic_codes; ++index ) {
            if ( match( value, basic_codes[index].name ) ) {
                d->resultCode = basic_codes[index].code;
                d->verbose = true;
                return;
            }
        }
        d->resultCode = QAtResult::UnknownError;
        d->verbose = true;

    }

    // Scan the extended code list for a match.
    for ( index = 0; index < num_ext_codes; ++index ) {
        if ( match( val, ext_codes[index].name ) ) {
            d->resultCode = ext_codes[index].code;
            d->verbose = true;
            return;
        }
    }
    d->resultCode = QAtResult::UnknownError;
    d->verbose = true;
}
void cdrop_widget::edit_entry_on_request(quint32 index)
{
    QString original_string_part = this->elements[index]->entry_original_string_part;
    //finding out the mime data and open a suiting dialog formular
    //the event_editor_dialogs folder
    if ( original_string_part.left( 8 ) == "show_txt" )
    {
        //this is a msg box !
        CEV_show_txt_widget* cev = new CEV_show_txt_widget( this->elements[index]->entry_original_string_part,
                                                            this->projectPath );
        QString new_osp = cev->exec2();
        if ( new_osp != this->elements[index]->entry_original_string_part )
        {
            this->elements[index]->entry_original_string_part = new_osp;
            this->elements[index]->entry_text = "\"" + cev->textbox->toPlainText() + "\"";
        }
        delete cev;
    }
    else if ( original_string_part.left(7) == "swi_mod" )
    {
        //this is a SetStuff Command!

    }
    else if ( original_string_part.left(7) == "var_mod" )
    {
        //this is a SetStuff Command!

    }
    else if ( original_string_part.left(7) == "txt_mod" )
    {
        //this is a SetStuff Command!

    }
    else if ( original_string_part.left(9) == "input_swi" )
    {
        //this is a input (switch) Dialog
    }
    else if ( original_string_part.left(9) == "input_var" )
    {
        //this is a input (variables) Dialog
    }
    else if ( original_string_part.left(9) == "input_txt" )
    {
        //this is a input (text) Dialog
    }
    else if ( original_string_part.left(12) == "input_choice" )
    {
        //this is a multiply choice dialog
    }
    else if ( original_string_part.left(4) == "wait" )
    {
        //this is a simple delay command
//        QString s = this->elements[index]->entry_original_string_part;
//        s.remove( "wait" );
//        s.remove( "|" );
//        quint32 w = QInputDialog::getInteger( this,
//                                              tr( "Edit Wait" ),
//                                              tr( "How much milliseconds shall be done nothing?" ),
//                                              s.toInt(),
//                                              100,360000);
    }
    else if ( original_string_part.left(7) == "comment" )
    {
        //this is a simple comment like the c++ "//" ones are
        QString s = QInputDialog::getText( this, tr( "Edit comment" ),
                                           tr( "Type comment's' new text" ),
                                           QLineEdit::Normal,
                                           this->elements[index]->entry_text );
        if ( !s.isEmpty() )
        {
            this->elements[index]->entry_text = s;
            s.prepend( "comment" );
            s.append( "|" );
            this->elements[index]->entry_original_string_part = s;
        }

    }
    else if ( original_string_part.left(15) == "change_matrix_s" )
    {
        //this is brutal function::
        //changing a single value in the matrix
    }
    else if ( original_string_part.left(15) == "change_matrix_m" )
    {
        //this is brutal function::
        //changing a value in the matrix to another given value
    }
    else if ( original_string_part.left(9) == "forrepeat" )
    {
        //this marks the restart of a for-routine
        //** this is NOT EDITABLE
    }
    else if ( original_string_part.left(3) == "for" )
    {
        //this marks the start of a for-routine
    }

    else if ( original_string_part.left(9) == "break_for" )
    {
        //this marks the end of the current for-routine
        //** this is NOT EDITABLE
    }
    else if ( original_string_part.left(7) == "if_else" )
    {
        //this marks the start of a container that only gets executed
        //when it's conditions match
         //** this is NOT EDITABLE
    }
    else if ( original_string_part.left(7) == "fi_else" )
    {
        //this marks the end of a container that only gets executed
        //when it's conditions match
         //** this is NOT EDITABLE
    }
    else if ( original_string_part.left(2) == "if" )
    {
        //editing if
        CEV_if_dialog_widget* cev = new CEV_if_dialog_widget( this->elements[index]->entry_original_string_part,
                                                              this->names_bools,
                                                              this->names_vars);
        QString new_osp = cev->exec2();
        if ( new_osp != this->elements[index]->entry_original_string_part )
        {
            this->elements[index]->entry_original_string_part = new_osp;
            this->elements[index]->entry_text = "if( " + new_osp + " )";
        }
        delete cev;
    }
    else if ( original_string_part.left(2) == "fi" )
    {
        //this marks the end of the current if container
        //** this is NOT EDITABLE
    }
}
Example #3
0
 int questionDialog(QWidget *parent, const QString &actionText, const QString &itemText, const QString &templateText, const QString &valueText)
 {
     return QMessageBox::question(parent,titleTemaple.arg(actionText).arg(itemText),templateText.arg(actionText).arg(itemText.toLower()).arg(valueText), QMessageBox::Yes, QMessageBox::No, QMessageBox::NoButton);
 }
Example #4
0
void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg)
{
    Q_UNUSED(context);
    const char *category = (type == QtDebugMsg) ? "qt" : NULL;
    LogPrint(category, "GUI: %s\n", msg.toStdString());
}
bool GerritOptionsPage::matches(const QString &s) const
{
    return s.contains(QLatin1String("gerrit"), Qt::CaseInsensitive);
}
bool QLandmarkFileHandlerLmx::readCoordinates(QLandmark &landmark)
{
    /*
    <xsd:complexType name="coordinatesType">
        <xsd:sequence>
            <xsd:element name="latitude">
                <xsd:simpleType>
                    <xsd:restriction base="xsd:double">
                        <xsd:minInclusive value="-90"/>
                        <xsd:maxInclusive value="90"/>
                    </xsd:restriction>
                </xsd:simpleType>
            </xsd:element>
            <xsd:element name="longitude">
                <xsd:simpleType>
                    <xsd:restriction base="xsd:double">
                        <xsd:minInclusive value="-180"/>
                        <xsd:maxExclusive value="180"/>
                    </xsd:restriction>
                </xsd:simpleType>
            </xsd:element>
            <xsd:element name="altitude" type="xsd:float" minOccurs="0" />
            <xsd:element name="horizontalAccuracy" minOccurs="0">
                <xsd:simpleType>
                    <xsd:restriction base="xsd:float">
                        <xsd:minInclusive value="0"/>
                    </xsd:restriction>
                </xsd:simpleType>
            </xsd:element>
            <xsd:element name="verticalAccuracy" minOccurs="0">
                <xsd:simpleType>
                    <xsd:restriction base="xsd:float">
                        <xsd:minInclusive value="0"/>
                    </xsd:restriction>
                </xsd:simpleType>
            </xsd:element>
            <xsd:element name="timeStamp" type="xsd:dateTime" minOccurs="0" />
        </xsd:sequence>
    </xsd:complexType>
    */

    Q_ASSERT(m_reader->isStartElement() &&
             (m_reader->name() == "coordinates"));

    if (!m_reader->readNextStartElement()) {
        m_reader->raiseError("The element \"coordinates\" did not have the required child element \"latitude\".");
        return false;
    }

    if (m_reader->name() == "latitude") {
        bool ok = false;
        QString s = m_reader->readElementText();

        if ((s == "INF") || (s == "-INF") || (s == "NaN")) {
            m_reader->raiseError(QString("The element \"latitude\" expected a value convertable to type double (value was \"%1\").").arg(s));
            return false;
        }

        double lat = s.toDouble(&ok);

        if (!ok) {
            m_reader->raiseError(QString("The element \"latitude\" expected a value convertable to type double (value was \"%1\").").arg(s));
            return false;
        }

        if (lat < -90.0 || 90.0 < lat) {
            m_reader->raiseError(QString("The element \"latitude\" fell outside of the bounds -90.0 <= latitude <= 90.0 (value was \"%1\").").arg(s));
            return false;
        }

        QGeoCoordinate coord = landmark.coordinate();
        coord.setLatitude(lat);
        landmark.setCoordinate(coord);

        if (!m_reader->readNextStartElement()) {
            m_reader->raiseError("The element \"coordinates\" did not have the required child element \"longitude\".");
            return false;
        }
    } else {
        m_reader->raiseError("The element \"coordinates\" did not have the required child element \"latitude\".");
        return false;
    }

    if (m_reader->name() == "longitude") {
        bool ok = false;
        QString s = m_reader->readElementText();

        if ((s == "INF") || (s == "-INF") || (s == "NaN")) {
            m_reader->raiseError(QString("The element \"longitude\" expected a value convertable to type double (value was \"%1\").").arg(s));
            return false;
        }

        double lon = s.toDouble(&ok);

        if (!ok) {
            m_reader->raiseError(QString("The element \"longitude\" expected a value convertable to type double (value was \"%1\").").arg(s));
            return false;
        }

        if (lon < -180.0 || 180.0 <= lon) {
            m_reader->raiseError(QString("The element \"longitude\" fell outside of the bounds -180.0 <= longitude < 180.0 (value was \"%1\").").arg(s));
            return false;
        }

        QGeoCoordinate coord = landmark.coordinate();
        coord.setLongitude(lon);
        landmark.setCoordinate(coord);

        if (!m_reader->readNextStartElement())
            return true;
    } else {
        m_reader->raiseError("The element \"coordinates\" did not have the required child element \"longitude\".");
        return false;
    }

    if (m_reader->name() == "altitude") {
        bool ok = false;
        QString s = m_reader->readElementText();

        if ((s == "INF") || (s == "-INF") || (s == "NaN")) {
            m_reader->raiseError(QString("The element \"altitude\" expected a value convertable to type double (value was \"%1\").").arg(s));
            return false;
        }

        double alt = s.toDouble(&ok);

        if (!ok) {
            m_reader->raiseError(QString("The element \"altitude\" expected a value convertable to type float (value was \"%1\").").arg(s));
            return false;
        }

        QGeoCoordinate coord = landmark.coordinate();
        coord.setAltitude(alt);
        landmark.setCoordinate(coord);

        if (!m_reader->readNextStartElement())
            return true;
    }

    QList<QString> names;
    names << "horizontalAccuracy";
    names << "verticalAccuracy";
    names << "timeStamp";

    for (int i = 0; i < names.size(); ++i) {
        // Not used outside of schema compliance check
        if (m_reader->name() == names.at(i)) {
           m_reader->skipCurrentElement();
           if (!m_reader->readNextStartElement())
               return true;
        }
    }

    m_reader->raiseError(QString("The element \"coordinate\" did not expect a child element named \"%1\" at this point (unknown child element or child element out of order).").arg(m_reader->name().toString()));
    return false;
}
Example #7
0
QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx)
{
    QString strHTML;

    LOCK2(cs_main, wallet->cs_wallet);
    strHTML.reserve(4000);
    strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";

    int64_t nTime = wtx.GetTxTime();
    int64_t nCredit = wtx.GetCredit();
    int64_t nDebit = wtx.GetDebit();
    int64_t nNet = nCredit - nDebit;

    strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx);
    int nRequests = wtx.GetRequestCount();
    if (nRequests != -1)
    {
        if (nRequests == 0)
            strHTML += tr(", has not been successfully broadcast yet");
        else if (nRequests > 0)
            strHTML += tr(", broadcast through %n node(s)", "", nRequests);
    }
    strHTML += "<br>";

    strHTML += "<b>" + tr("Date") + ":</b> " + (nTime ? GUIUtil::dateTimeStr(nTime) : "") + "<br>";

    //
    // From
    //
    if (wtx.IsCoinBase() || wtx.IsCoinStake())
    {
        strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>";
    }
    else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty())
    {
        // Online transaction
        strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>";
    }
    else
    {
        // Offline transaction
        if (nNet > 0)
        {
            // Credit
            BOOST_FOREACH(const CTxOut& txout, wtx.vout)
            {
                if (wallet->IsMine(txout))
                {
                    CTxDestination address;
                    if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address))
                    {
                        if (wallet->mapAddressBook.count(address))
                        {
                            strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>";
                            strHTML += "<b>" + tr("To") + ":</b> ";
                            strHTML += GUIUtil::HtmlEscape(CBitcoinAddress(address).ToString());
                            if (!wallet->mapAddressBook[address].empty())
                                strHTML += " (" + tr("own address") + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + ")";
                            else
                                strHTML += " (" + tr("own address") + ")";
                            strHTML += "<br>";
                        }
                    }
                    break;
                }
            }
        }
    }
Example #8
0
QString Serveur::parseCommande(QString comm,bool serveur)
{
    if(comm.startsWith("/"))
    {
        comm.remove(0,1);
        QString pref=comm.split(" ").first();
        QStringList args=comm.split(" ");
        args.removeFirst();
        QString destChan=tab->tabText(tab->currentIndex());
        QString msg=args.join(" ");

        if(pref=="me")
            return "PRIVMSG "+destChan+" ACTION " + msg + "";
        else if(pref=="msg")
            return "MSG "+destChan+" ACTION " + msg + "";
        else if(pref=="join")
        {
            join(msg);
            return " ";
        }
        else if(pref=="quit")
        {
            if(msg == "")
                return "QUIT "+msgQuit;
            else
                return "QUIT "+msg;
        }
        else if(pref=="part")
        {
            tab->removeTab(tab->currentIndex());

            if(msg == "")
            {
                if(msg.startsWith("#"))
                    destChan=msg.split(" ").first();

                if(msgQuit=="")
                    return "PART "+destChan+" using IrcLightClient";
                else
                    return "PART "+destChan+" "+msgQuit;
            }
            else
                return "PART "+destChan+" "+msg;

            conversations.remove(destChan);
        }
        else if(pref=="kick")
        {
            QStringList tableau=msg.split(" ");
            QString c1,c2,c3;
            if(tableau.count() > 0) c1=" "+tableau.first();
            else c1="";
            if(tableau.count() > 1) c2=" "+tableau.at(1);
            else c2="";
            if(tableau.count() > 2) c3=" "+tableau.at(2);
            else c3="";

            if(c1.startsWith("#"))
                return "KICK"+c1+c2+c3;
            else
                return "KICK "+destChan+c1+c2;
        }
        else if(pref=="update")
        {
            updateUsers=true;
            return "WHO "+destChan;
        }
        else if(pref=="ns")
        {
            return "NICKSERV "+msg;
        }
        else if(pref=="nick")
        {
            emit pseudoChanged(msg);
                        ecrire("-> Nickname changed to "+msg);
            return "NICK "+msg;
        }
        else if(pref=="msg")
        {
            return "MSG "+msg;
        }

        else
            return pref+" "+msg;
    }
    else if(!serveur)
	{
        QString destChan=tab->tabText(tab->currentIndex());
                if(comm.endsWith("<br />"))
                    comm=comm.remove(QRegExp("<br />$"));
                ecrire("<b>&lt;"+pseudo+"&gt;</b> "+comm,destChan);

        if(comm.startsWith(":"))
            comm.insert(0,":");

        return "PRIVMSG "+destChan+" "+comm.replace(" ","\t");
    }
	else
	{
		return "";
	}
}
Example #9
0
void CharmNewReleaseDialog::setReleaseInformationLink(const QString &link)
{
    QString hyperlink = m_ui->releaseInfoLabel->text();
    hyperlink.replace(QLatin1String("LINK"), link);
    m_ui->releaseInfoLabel->setText(hyperlink);
}
QNetworkReplyFileImpl::QNetworkReplyFileImpl(QObject *parent, const QNetworkRequest &req, const QNetworkAccessManager::Operation op)
    : QNetworkReply(*new QNetworkReplyFileImplPrivate(), parent)
{
    setRequest(req);
    setUrl(req.url());
    setOperation(op);
    setFinished(true);
    QNetworkReply::open(QIODevice::ReadOnly);

    QNetworkReplyFileImplPrivate *d = (QNetworkReplyFileImplPrivate*) d_func();

    QUrl url = req.url();
    if (url.host() == QLatin1String("localhost"))
        url.setHost(QString());

#if !defined(Q_OS_WIN)
    // do not allow UNC paths on Unix
    if (!url.host().isEmpty()) {
        // we handle only local files
        QString msg = QCoreApplication::translate("QNetworkAccessFileBackend", "Request for opening non-local file %1").arg(url.toString());
        setError(QNetworkReply::ProtocolInvalidOperationError, msg);
        QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
            Q_ARG(QNetworkReply::NetworkError, QNetworkReply::ProtocolInvalidOperationError));
        QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
        return;
    }
#endif
    if (url.path().isEmpty())
        url.setPath(QLatin1String("/"));
    setUrl(url);


    QString fileName = url.toLocalFile();
    if (fileName.isEmpty()) {
        if (url.scheme() == QLatin1String("qrc")) {
            fileName = QLatin1Char(':') + url.path();
        } else {
#if defined(Q_OS_ANDROID)
            if (url.scheme() == QLatin1String("assets"))
                fileName = QLatin1String("assets:") + url.path();
            else
#endif
                fileName = url.toString(QUrl::RemoveAuthority | QUrl::RemoveFragment | QUrl::RemoveQuery);
        }
    }

    QFileInfo fi(fileName);
    if (fi.isDir()) {
        QString msg = QCoreApplication::translate("QNetworkAccessFileBackend", "Cannot open %1: Path is a directory").arg(url.toString());
        setError(QNetworkReply::ContentOperationNotPermittedError, msg);
        QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
            Q_ARG(QNetworkReply::NetworkError, QNetworkReply::ContentOperationNotPermittedError));
        QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
        return;
    }

    d->realFile.setFileName(fileName);
    bool opened = d->realFile.open(QIODevice::ReadOnly | QIODevice::Unbuffered);

    // could we open the file?
    if (!opened) {
        QString msg = QCoreApplication::translate("QNetworkAccessFileBackend", "Error opening %1: %2")
                .arg(d->realFile.fileName(), d->realFile.errorString());

        if (d->realFile.exists()) {
            setError(QNetworkReply::ContentAccessDenied, msg);
            QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
                Q_ARG(QNetworkReply::NetworkError, QNetworkReply::ContentAccessDenied));
        } else {
            setError(QNetworkReply::ContentNotFoundError, msg);
            QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
                Q_ARG(QNetworkReply::NetworkError, QNetworkReply::ContentNotFoundError));
        }
        QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
        return;
    }

    setHeader(QNetworkRequest::LastModifiedHeader, fi.lastModified());
    d->realFileSize = fi.size();
    setHeader(QNetworkRequest::ContentLengthHeader, d->realFileSize);

    QMetaObject::invokeMethod(this, "metaDataChanged", Qt::QueuedConnection);
    QMetaObject::invokeMethod(this, "downloadProgress", Qt::QueuedConnection,
        Q_ARG(qint64, d->realFileSize), Q_ARG(qint64, d->realFileSize));
    QMetaObject::invokeMethod(this, "readyRead", Qt::QueuedConnection);
    QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
}
Example #11
0
QString DynamicPathConverter::convert(QString const &data) const
{
	QString mutablePath = mPathFromRoot;
	return readTemplate(mutablePath.replace("@@DATA@@", data));
}
Example #12
0
void HelpMessageBox::printToConsole()
{
    // On other operating systems, the expected action is to print the message to the console.
    QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
    fprintf(stderr, "%s", strUsage.toStdString().c_str());
}
bool KviPerlInterpreter::execute(
    const QString &szCode,
    QStringList &args,
    QString &szRetVal,
    QString &szError,
    QStringList &lWarnings)
{
    if(!m_pInterpreter)
    {
        szError = __tr2qs_ctx("Internal error: perl interpreter not initialized","perl");
        return false;
    }

    g_lWarningList.clear();

    QByteArray szUtf8 = szCode.toUtf8();
    PERL_SET_CONTEXT(m_pInterpreter);

    // clear the _ array
    AV * pArgs = get_av("_",1);
    SV * pArg = av_shift(pArgs);
    while(SvOK(pArg))
    {
        SvREFCNT_dec(pArg);
        pArg = av_shift(pArgs);
    }

    if(args.count() > 0)
    {
        // set the args in the _ arry
        av_unshift(pArgs,(I32)args.count());
        int idx = 0;
        for(QStringList::Iterator it = args.begin(); it != args.end(); ++it)
        {
            QString tmp = *it;
            const char * val = tmp.toUtf8().data();
            if(val)
            {
                pArg = newSVpv(val,tmp.length());
                if(!av_store(pArgs,idx,pArg))
                    SvREFCNT_dec(pArg);
            }
            idx++;
        }
    }

    // call the code
    SV * pRet = eval_pv(szUtf8.data(),false);

    // clear the _ array again
    pArgs = get_av("_",1);
    pArg = av_shift(pArgs);
    while(SvOK(pArg))
    {
        SvREFCNT_dec(pArg);
        pArg = av_shift(pArgs);
    }
    av_undef(pArgs);

    // get the ret value
    if(pRet)
    {
        if(SvOK(pRet))
            szRetVal = svToQString(pRet);
    }

    if(!g_lWarningList.isEmpty())
        lWarnings = g_lWarningList;

    // and the eventual error string
    pRet = get_sv("@",false);
    if(pRet)
    {
        if(SvOK(pRet))
        {
            szError = svToQString(pRet);
            if(!szError.isEmpty())return false;
        }
    }

    return true;
}
Example #14
0
	void Plugin::UploadTo (LIBMTP_mtpdevice_t *device, const QByteArray& storageId,
			const QString& localPath, const QString& origPath)
	{
		if (!device->storage)
			LIBMTP_Get_Storage (device, 0);

		auto storage = device->storage;

		while (storage)
		{
			qDebug () << "st" << storage->id;
			if (QByteArray::number (storage->id) == storageId)
				break;
			storage = storage->next;
		}

		if (!storage)
		{
			qWarning () << Q_FUNC_INFO
					<< "could not find storage"
					<< storageId;
			emit uploadFinished (localPath,
					QFile::ResourceError,
					tr ("Unable to find the requested storage."));
			return;
		}

		const auto id = storage->id;
		const auto& info = OrigInfos_.take (origPath);

		qDebug () << "uploading" << localPath << "of type" << GetFileType (info.FileFormat_) << "to" << storage->id;

		auto track = LIBMTP_new_track_t ();
		track->storage_id = id;

		auto getStr = [] (const QString& str) { return strdup (str.toUtf8 ().constData ()); };

		track->filename = getStr (QFileInfo (localPath).fileName ());
		track->album = getStr (info.Album_);
		track->title = getStr (info.TrackTitle_);
		track->genre = getStr (info.Genres_.join ("; "));
		track->artist = getStr (info.Artist_);
		track->tracknumber = info.TrackNumber_;
		track->filetype = GetFileType (info.FileFormat_);
		track->filesize = QFileInfo (localPath).size ();
		track->date = getStr (QString::number (info.AlbumYear_) + "0101T0000.0");

		auto watcher = new QFutureWatcher<UploadInfo> ();
		connect (watcher,
				SIGNAL (finished ()),
				this,
				SLOT (handleUploadFinished ()));
		const auto future = QtConcurrent::run ([=] () -> UploadInfo
			{
				const auto cbData = new CallbackData { this, 0 };
				const auto res = LIBMTP_Send_Track_From_File (device,
						localPath.toUtf8 ().constData (), track,
						TransferCallback, cbData);
				delete cbData;
				return { res, device, localPath, track, info };
			});
		watcher->setFuture (future);
	}
Example #15
0
void PropertyModel::addProperty(PropertyID propID, EPropertyType propType,
    const QString& propName, const QVariant& value, const QString& uiHint)
{
    if(!_propIdMap.contains(propID))
    {
        Property* prop;

        switch(propType)
        {
        case EPropertyType::Boolean:
            prop = new BooleanProperty(propName, value.toBool());
            break;
        case EPropertyType::Integer:
            prop = new IntegerProperty(propName, value.toInt());
            break;
        case EPropertyType::Double:
            prop = new DoubleProperty(propName, value.toDouble());
            break;
        case EPropertyType::Enum:
            prop = new EnumProperty(propName, value.value<Enum>());
            break;
        case EPropertyType::Matrix:
            prop = new MatrixProperty(propName, value.value<Matrix3x3>());
            break;
        case EPropertyType::Filepath:
            prop = new FilePathProperty(propName, value.value<Filepath>());
            break;
        case EPropertyType::String:
            prop = new StringProperty(propName, value.toString());
            break;
        default:
            /// TODO: throw ??
            return;
        }

        if(!uiHint.isEmpty())
        {
            PropertyHintList uiHintsLists;
            QRegExp re(QString("([^= ]*):{1}([^,]*),?"));
            re.setMinimal(false);
            int pos = 0;

            while((pos = re.indexIn(uiHint, pos)) != -1)
            {
                uiHintsLists.append(qMakePair(re.cap(1), re.cap(2).trimmed()));
                pos += re.matchedLength();
            }

            if(!uiHintsLists.isEmpty())
                prop->setUiHints(uiHintsLists);
        }

        prop->setPropertyID(propID);
        _propIdMap.insert(propID, prop);
        _currentGroup->appendChild(prop);
    }
    else
    {
        /// TODO: throw ??
    }
}
QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx)
{
    QString strHTML;

    {
        LOCK(wallet->cs_wallet);
        strHTML.reserve(4000);
        strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";

        int64 nTime = wtx.GetTxTime();
        int64 nCredit = wtx.GetCredit();
        int64 nDebit = wtx.GetDebit();
        int64 nNet = nCredit - nDebit;

        strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx);
        int nRequests = wtx.GetRequestCount();
        if (nRequests != -1)
        {
            if (nRequests == 0)
                strHTML += tr(", has not been successfully broadcast yet");
            else if (nRequests > 0)
                strHTML += tr(", broadcast through %n node(s)", "", nRequests);
        }
        strHTML += "<br>";

        strHTML += "<b>" + tr("Date") + ":</b> " + (nTime ? GUIUtil::dateTimeStr(nTime) : "") + "<br>";

        //
        // From
        //
        if (wtx.IsCoinBase())
        {
            strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>";
        }
        else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty())
        {
            // Online transaction
            strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>";
        }
        else
        {
            // Offline transaction
            if (nNet > 0)
            {
                // Credit
                BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                {
                    if (wallet->IsMine(txout))
                    {
                        CTxDestination address;
                        if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address))
                        {
                            if (wallet->mapAddressBook.count(address))
                            {
                                strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>";
                                strHTML += "<b>" + tr("To") + ":</b> ";
                                strHTML += GUIUtil::HtmlEscape(CBitcoinAddress(address).ToString());
                                if (!wallet->mapAddressBook[address].empty())
                                    strHTML += " (" + tr("own address") + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + ")";
                                else
                                    strHTML += " (" + tr("own address") + ")";
                                strHTML += "<br>";
                            }
                        }
                        break;
                    }
                }
            }
        }

        //
        // To
        //
        if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty())
        {
            // Online transaction
            std::string strAddress = wtx.mapValue["to"];
            strHTML += "<b>" + tr("To") + ":</b> ";
            CTxDestination dest = CBitcoinAddress(strAddress).Get();
            if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].empty())
                strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest]) + " ";
            strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>";
        }

        //
        // Amount
        //
        if (wtx.IsCoinBase() && nCredit == 0)
        {
            //
            // Coinbase
            //
            int64 nUnmatured = 0;
            BOOST_FOREACH(const CTxOut& txout, wtx.vout)
            nUnmatured += wallet->GetCredit(txout);
            strHTML += "<b>" + tr("Credit") + ":</b> ";
            if (wtx.IsInMainChain())
                strHTML += BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")";
            else
                strHTML += "(" + tr("not accepted") + ")";
            strHTML += "<br>";
        }
QString qDBusIntrospectObject(const QDBusConnectionPrivate::ObjectTreeNode &node, const QString &path)
{
    // object may be null

    QString xml_data(QLatin1String(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE));
    xml_data += QLatin1String("<node>\n");

    if (node.obj) {
        Q_ASSERT_X(QThread::currentThread() == node.obj->thread(),
                   "QDBusConnection: internal threading error",
                   "function called for an object that is in another thread!!");

        if (node.flags & (QDBusConnection::ExportScriptableContents
                           | QDBusConnection::ExportNonScriptableContents)) {
            // create XML for the object itself
            const QMetaObject *mo = node.obj->metaObject();
            for ( ; mo != &QObject::staticMetaObject; mo = mo->superClass())
                xml_data += qDBusGenerateMetaObjectXml(node.interfaceName, mo, mo->superClass(),
                                                       node.flags);
        }

        // does this object have adaptors?
        QDBusAdaptorConnector *connector;
        if (node.flags & QDBusConnection::ExportAdaptors &&
            (connector = qDBusFindAdaptorConnector(node.obj))) {

            // trasverse every adaptor in this object
            QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin();
            QDBusAdaptorConnector::AdaptorMap::ConstIterator end = connector->adaptors.constEnd();
            for ( ; it != end; ++it) {
                // add the interface:
                QString ifaceXml = QDBusAbstractAdaptorPrivate::retrieveIntrospectionXml(it->adaptor);
                if (ifaceXml.isEmpty()) {
                    // add the interface's contents:
                    ifaceXml += qDBusGenerateMetaObjectXml(QString::fromLatin1(it->interface),
                                                           it->adaptor->metaObject(),
                                                           &QDBusAbstractAdaptor::staticMetaObject,
                                                           QDBusConnection::ExportScriptableContents
                                                           | QDBusConnection::ExportNonScriptableContents);

                    QDBusAbstractAdaptorPrivate::saveIntrospectionXml(it->adaptor, ifaceXml);
                }

                xml_data += ifaceXml;
            }
        }

        // is it a virtual node that handles introspection itself?
        if (node.flags & QDBusConnectionPrivate::VirtualObject) {
            xml_data += node.treeNode->introspect(path);
        }

        xml_data += QLatin1String( propertiesInterfaceXml );
    }

    xml_data += QLatin1String( introspectableInterfaceXml );
    xml_data += QLatin1String( peerInterfaceXml );

    if (node.flags & QDBusConnection::ExportChildObjects) {
        xml_data += generateSubObjectXml(node.obj);
    } else {
        // generate from the object tree
        QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it =
            node.children.constBegin();
        QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator end =
            node.children.constEnd();
        for ( ; it != end; ++it)
            if (it->obj || !it->children.isEmpty())
                xml_data += QString::fromLatin1("  <node name=\"%1\"/>\n")
                            .arg(it->name);
    }

    xml_data += QLatin1String("</node>\n");
    return xml_data;
}
Example #18
0
void SettingsDialog::saveToSettings()
{
    QSettings settings;
    settings.beginGroup(QLatin1String("Settings"));
    settings.setValue(QLatin1String("currentTab"), tabWidget->currentIndex());
    settings.endGroup();

    settings.beginGroup(QLatin1String("MainWindow"));
    settings.setValue(QLatin1String("home"), homeLineEdit->text());
    settings.setValue(QLatin1String("startupBehavior"), startupBehavior->currentIndex());
    settings.endGroup();

    settings.beginGroup(QLatin1String("downloadmanager"));
    settings.setValue(QLatin1String("alwaysPromptForFileName"), downloadAsk->isChecked());
    settings.setValue(QLatin1String("downloadDirectory"), downloadsLocation->text());
    settings.setValue(QLatin1String("external"), externalDownloadButton->isChecked());
    settings.setValue(QLatin1String("externalPath"), externalDownloadPath->text());
    settings.endGroup();

    settings.beginGroup(QLatin1String("history"));
    int historyExpire = expireHistory->currentIndex();
    int idx = -1;
    switch (historyExpire) {
    case 0: idx = 1; break;
    case 1: idx = 7; break;
    case 2: idx = 14; break;
    case 3: idx = 30; break;
    case 4: idx = 365; break;
    case 5: idx = -1; break;
    case 6: idx = -2; break;
    }
    settings.setValue(QLatin1String("historyLimit"), idx);
    settings.endGroup();

    settings.beginGroup(QLatin1String("urlloading"));
    settings.setValue(QLatin1String("searchEngineFallback"), searchEngineFallback->isChecked());
    settings.endGroup();

    // Appearance
    settings.beginGroup(QLatin1String("websettings"));
    settings.setValue(QLatin1String("fixedFont"), m_fixedFont);
    settings.setValue(QLatin1String("standardFont"), m_standardFont);

    settings.setValue(QLatin1String("blockPopupWindows"), blockPopupWindows->isChecked());
    settings.setValue(QLatin1String("enableJavascript"), enableJavascript->isChecked());
    settings.setValue(QLatin1String("enablePlugins"), enablePlugins->isChecked());
    settings.setValue(QLatin1String("enableImages"), enableImages->isChecked());
    settings.setValue(QLatin1String("enableLocalStorage"), enableLocalStorage->isChecked());
    QString userStyleSheetString = userStyleSheet->text();
    if (QFile::exists(userStyleSheetString))
        settings.setValue(QLatin1String("userStyleSheet"), QUrl::fromLocalFile(userStyleSheetString));
    else
        settings.setValue(QLatin1String("userStyleSheet"), QUrl::fromEncoded(userStyleSheetString.toUtf8()));
    settings.setValue(QLatin1String("enableClickToFlash"), clickToFlash->isChecked());

    if (minimFontSizeCheckBox->isChecked())
        settings.setValue(QLatin1String("minimumFontSize"), minimumFontSizeSpinBox->value());
    else
        settings.setValue(QLatin1String("minimumFontSize"), 0);
    settings.endGroup();

    // Privacy
    settings.beginGroup(QLatin1String("cookies"));
    CookieJar::AcceptPolicy acceptCookies;
    switch (acceptCombo->currentIndex()) {
    default:
    case 0:
        acceptCookies = CookieJar::AcceptAlways;
        break;
    case 1:
        acceptCookies = CookieJar::AcceptNever;
        break;
    case 2:
        acceptCookies = CookieJar::AcceptOnlyFromSitesNavigatedTo;
        break;
    }

    QMetaEnum acceptPolicyEnum = CookieJar::staticMetaObject.enumerator(CookieJar::staticMetaObject.indexOfEnumerator("AcceptPolicy"));
    settings.setValue(QLatin1String("acceptCookies"), QLatin1String(acceptPolicyEnum.valueToKey(acceptCookies)));

    CookieJar::KeepPolicy keepPolicy;
    switch (keepUntilCombo->currentIndex()) {
    default:
    case 0:
        keepPolicy = CookieJar::KeepUntilExpire;
        break;
    case 1:
        keepPolicy = CookieJar::KeepUntilExit;
        break;
    case 2:
        keepPolicy = CookieJar::KeepUntilTimeLimit;
        break;
    }

    QMetaEnum keepPolicyEnum = CookieJar::staticMetaObject.enumerator(CookieJar::staticMetaObject.indexOfEnumerator("KeepPolicy"));
    settings.setValue(QLatin1String("keepCookiesUntil"), QLatin1String(keepPolicyEnum.valueToKey(keepPolicy)));
    int sessionLength = cookieSessionCombo->currentIndex();
    switch (sessionLength) {
    case 1: sessionLength = 1; break;
    case 2: sessionLength = 2; break;
    case 3: sessionLength = 3; break;
    case 4: sessionLength = 7; break;
    case 5: sessionLength = 30; break;
    default:
    case 0: sessionLength = -1; break;
    }
    settings.setValue(QLatin1String("sessionLength"), sessionLength);
    settings.setValue(QLatin1String("filterTrackingCookies"), filterTrackingCookiesCheckbox->isChecked());
    settings.endGroup();

    // Network
    settings.beginGroup(QLatin1String("network"));
    settings.setValue(QLatin1String("cacheEnabled"), networkCache->isChecked());
    settings.setValue(QLatin1String("maximumCacheSize"), networkCacheMaximumSizeSpinBox->value());
    settings.endGroup();

    // proxy
    settings.beginGroup(QLatin1String("proxy"));
    settings.setValue(QLatin1String("enabled"), proxySupport->isChecked());
    settings.setValue(QLatin1String("type"), proxyType->currentIndex());
    settings.setValue(QLatin1String("hostName"), proxyHostName->text());
    settings.setValue(QLatin1String("port"), proxyPort->text());
    settings.setValue(QLatin1String("userName"), proxyUserName->text());
    settings.setValue(QLatin1String("password"), proxyPassword->text());
    settings.endGroup();

    // Tabs
    settings.beginGroup(QLatin1String("tabs"));
    settings.setValue(QLatin1String("selectNewTabs"), selectTabsWhenCreated->isChecked());
    settings.setValue(QLatin1String("confirmClosingMultipleTabs"), confirmClosingMultipleTabs->isChecked());
    settings.setValue(QLatin1String("oneCloseButton"), oneCloseButton->isChecked());
    settings.setValue(QLatin1String("quitAsLastTabClosed"), quitAsLastTabClosed->isChecked());
    settings.setValue(QLatin1String("openTargetBlankLinksIn"), openTargetBlankLinksIn->currentIndex());
    settings.setValue(QLatin1String("openLinksFromAppsIn"), openLinksFromAppsIn->currentIndex());
    settings.endGroup();

    settings.beginGroup(QLatin1String("autofill"));
    settings.setValue(QLatin1String("passwordForms"), autoFillPasswordFormsCheckBox->isChecked());
    settings.endGroup();

    // Accessibility
#if QT_VERSION >= 0x040600 || defined(WEBKIT_TRUNK)
    settings.beginGroup(QLatin1String("WebView"));
    settings.setValue(QLatin1String("enableAccessKeys"), enableAccessKeys->isChecked());
    settings.endGroup();
#endif

    BrowserApplication::instance()->loadSettings();
    BrowserApplication::networkAccessManager()->loadSettings();
    BrowserApplication::cookieJar()->loadSettings();
    BrowserApplication::historyManager()->loadSettings();
    BrowserApplication::autoFillManager()->loadSettings();

    WebPage::webPluginFactory()->refreshPlugins();

    QList<BrowserMainWindow*> list = BrowserApplication::instance()->mainWindows();
    foreach (BrowserMainWindow *mainWindow, list) {
        mainWindow->tabWidget()->loadSettings();
    }
}
void testAssert(bool result, const QString& text = "Unknown") {
  if (!result) {
    KstTestFailed();
    printf("Test [%s] failed.\n", text.toLatin1().data());
  }
}
Example #20
0
QValidator::State MapimgValidator::validate( QString & input, int & ) const
{
   if( input.upper() == "UNDEFINED" && m_allowUndefined )
   {
       input = "Undefined";
       return Acceptable;
   }

   QRegExp empty( QString::fromLatin1(" *-?\\.? *") );
   if ( m_bottom >= 0 &&
      input.stripWhiteSpace().startsWith(QString::fromLatin1("-")) )
        return Invalid;
   if ( empty.exactMatch(input) )
      return Intermediate;
   bool ok = TRUE;
   double entered = input.toDouble( &ok );
   int nume = input.contains( 'e', FALSE );
   if ( !ok ) {
      // explicit exponent regexp
      QRegExp expexpexp( QString::fromLatin1("[Ee][+-]?\\d*$") );
      int eeePos = expexpexp.search( input );
      if ( eeePos > 0 && nume == 1 ) {
         QString mantissa = input.left( eeePos );
         entered = mantissa.toDouble( &ok );
         if ( !ok )
            return Invalid;
      } else if ( eeePos == 0 ) {
         return Intermediate;
      } else {
         return Invalid;
      }
   }

   QString tempInput = QString::number( entered );

   int tempj = tempInput.find( '.' );
   int i = input.find( '.' );

   if( (i >= 0 || tempj >= 0 || input.contains("e-", FALSE)) && m_decimals == 0 )
   {
      return Invalid;
   }

   if ( i >= 0 && nume == 0 ) {
      // has decimal point (but no E), now count digits after that
      i++;
      int j = i;
      while( input[j].isDigit() )
         j++;
      if ( j - i > m_decimals )
         return Invalid; //Intermediate;
   }

   if( entered > m_top )
      return Invalid;
   else if ( entered < m_bottom )
      return Intermediate;
   else
      return Acceptable;
}
bool QLandmarkFileHandlerLmx::readLandmark(QLandmark &landmark)
{
    /*
    <xsd:complexType name="landmarkType">
        <xsd:sequence>
            <xsd:element name="name" type="xsd:string" minOccurs="0" />
            <xsd:element name="description" type="xsd:string" minOccurs="0" />
            <xsd:element name="coordinates" type="coordinatesType" minOccurs="0" />
            <xsd:element name="coverageRadius" minOccurs="0">
                <xsd:simpleType>
                    <xsd:restriction base="xsd:float">
                        <xsd:minInclusive value="0"/>
                    </xsd:restriction>
                </xsd:simpleType>
            </xsd:element>
            <xsd:element name="addressInfo" type="addressInfoType" minOccurs="0" />
            <xsd:element name="mediaLink" type="mediaLinkType" minOccurs="0" maxOccurs="unbounded" />
            <xsd:element name="category" type="categoryType" minOccurs="0" maxOccurs="unbounded" />
        </xsd:sequence>
    </xsd:complexType>
    */

    if(m_cancel && (*m_cancel) == true) {
        m_errorCode = QLandmarkManager::CancelError;
        m_error = "Import of lmx file was canceled";
        return false;
    }

    Q_ASSERT(m_reader->isStartElement() &&
             (m_reader->name() == "landmark"));

    m_landmarkCategoryNames.append(QStringList());

    if (!m_reader->readNextStartElement())
        return true;

    if (m_reader->name() == "name") {
        landmark.setName(m_reader->readElementText());
        if (!m_reader->readNextStartElement())
            return true;
    }

    if (m_reader->name() == "description") {
        landmark.setDescription(m_reader->readElementText());
        if (!m_reader->readNextStartElement())
            return true;
    }

    if (m_reader->name() == "coordinates") {
        if (!readCoordinates(landmark))
            return false;

        if (!m_reader->readNextStartElement())
            return true;
    }

    if (m_reader->name() == "coverageRadius") {
        bool ok = false;
        QString s = m_reader->readElementText();

        if ((s == "INF") || (s == "-INF") || (s == "NaN")) {
            m_reader->raiseError(QString("The element \"coverageRadius\" expected a value convertable to type real (value was \"%1\").").arg(s));
            return false;
        }

        qreal rad = (qreal)(s.toDouble(&ok));

        if (!ok) {
            m_reader->raiseError(QString("The element \"coverageRadius\" expected a value convertable to type real (value was \"%1\").").arg(s));
            return false;
        }

        if (rad < 0.0) {
            m_reader->raiseError(QString("The element \"coverageRadius\" is expected to have a non-negative value (value was \"%1\").").arg(s));
            return false;
        }

        landmark.setRadius(rad);

        if (!m_reader->readNextStartElement())
            return true;
    }

    if (m_reader->name() == "addressInfo") {
        if (!readAddressInfo(landmark))
            return false;

        if (!m_reader->readNextStartElement())
            return true;
    }

    // TODO need to document the fact that only the first link is read
    // and the others are ignored
    bool mediaLinkRead = false;

    while (m_reader->name() == "mediaLink") {
        if (!mediaLinkRead) {
            mediaLinkRead = true;
            if (!readMediaLink(landmark))
                return false;
        }

        if (!m_reader->readNextStartElement())
            return true;
    }


    QStringList categoryNames;
    while (m_reader->name() == "category") {
        QString name;
        if (!readCategory(name))
            return false;
        categoryNames << name;

        if (!m_reader->readNextStartElement()) {
            m_landmarkCategoryNames.last() = categoryNames;
            return true;
        }
    }

    m_reader->raiseError(QString("The element \"landmark\" did not expect a child element named \"%1\" at this point (unknown child element or child element out of order).").arg(m_reader->name().toString()));
    return false;
}