void QDBusMetaObjectGenerator::write(QDBusMetaObject *obj)
{
    // this code here is mostly copied from qaxbase.cpp
    // with a few modifications to make it cleaner
    
    QString className = interface;
    className.replace(QLatin1Char('.'), QLatin1String("::"));
    if (className.isEmpty())
        className = QLatin1String("QDBusInterface");

    QVarLengthArray<int> idata;
    idata.resize(sizeof(QDBusMetaObjectPrivate) / sizeof(int));

    QDBusMetaObjectPrivate *header = reinterpret_cast<QDBusMetaObjectPrivate *>(idata.data());
    header->revision = 1;
    header->className = 0;
    header->classInfoCount = 0;
    header->classInfoData = 0;
    header->methodCount = methods.count();
    header->methodData = idata.size();
    header->propertyCount = properties.count();
    header->propertyData = header->methodData + header->methodCount * 5;
    header->enumeratorCount = 0;
    header->enumeratorData = 0;
    header->propertyDBusData = header->propertyData + header->propertyCount * 3;
    header->methodDBusData = header->propertyDBusData + header->propertyCount * intsPerProperty;

    int data_size = idata.size() +
                    (header->methodCount * (5+intsPerMethod)) +
                    (header->propertyCount * (3+intsPerProperty));
    foreach (const Method &mm, methods)
        data_size += 2 + mm.inputTypes.count() + mm.outputTypes.count();
    idata.resize(data_size + 1);

    char null('\0');
    QByteArray stringdata = className.toLatin1();
    stringdata += null;
    stringdata.reserve(8192);

    int offset = header->methodData;
    int signatureOffset = header->methodDBusData;
    int typeidOffset = header->methodDBusData + header->methodCount * intsPerMethod;
    idata[typeidOffset++] = 0;                           // eod

    // add each method:
    for (QMap<QByteArray, Method>::ConstIterator it = methods.constBegin();
         it != methods.constEnd(); ++it) {
        // form "prototype\0parameters\0typeName\0tag\0methodname\0inputSignature\0outputSignature"
        const Method &mm = it.value();

        idata[offset++] = stringdata.length();
        stringdata += it.key();                 // prototype
        stringdata += null;
        idata[offset++] = stringdata.length();
        stringdata += mm.parameters;
        stringdata += null;
        idata[offset++] = stringdata.length();
        stringdata += mm.typeName;
        stringdata += null;
        idata[offset++] = stringdata.length();
        stringdata += mm.tag;
        stringdata += null;
        idata[offset++] = mm.flags;

        idata[signatureOffset++] = stringdata.length();
        stringdata += mm.name;
        stringdata += null;
        idata[signatureOffset++] = stringdata.length();
        stringdata += mm.inputSignature;
        stringdata += null;
        idata[signatureOffset++] = stringdata.length();
        stringdata += mm.outputSignature;
        stringdata += null;

        idata[signatureOffset++] = typeidOffset;
        idata[typeidOffset++] = mm.inputTypes.count();
        memcpy(idata.data() + typeidOffset, mm.inputTypes.data(), mm.inputTypes.count() * sizeof(int));
        typeidOffset += mm.inputTypes.count();

        idata[signatureOffset++] = typeidOffset;
        idata[typeidOffset++] = mm.outputTypes.count();
        memcpy(idata.data() + typeidOffset, mm.outputTypes.data(), mm.outputTypes.count() * sizeof(int));
        typeidOffset += mm.outputTypes.count();
    }

    Q_ASSERT(offset == header->propertyData);
    Q_ASSERT(signatureOffset == header->methodDBusData + header->methodCount * intsPerMethod);
    Q_ASSERT(typeidOffset == idata.size());

    // add each property
    signatureOffset = header->propertyDBusData;
    for (QMap<QByteArray, Property>::ConstIterator it = properties.constBegin();
         it != properties.constEnd(); ++it) {
        const Property &mp = it.value();

        // form is "name\0typeName\0signature\0"
        idata[offset++] = stringdata.length();
        stringdata += it.key();                 // name
        stringdata += null;
        idata[offset++] = stringdata.length();
        stringdata += mp.typeName;
        stringdata += null;
        idata[offset++] = mp.flags;

        idata[signatureOffset++] = stringdata.length();
        stringdata += mp.signature;
        stringdata += null;
        idata[signatureOffset++] = mp.type;
    }

    Q_ASSERT(offset == header->propertyDBusData);
    Q_ASSERT(signatureOffset == header->methodDBusData);

    char *string_data = new char[stringdata.length()];
    memcpy(string_data, stringdata, stringdata.length());

    uint *uint_data = new uint[idata.size()];
    memcpy(uint_data, idata.data(), idata.size() * sizeof(int));

    // put the metaobject together
    obj->d.data = uint_data;
    obj->d.extradata = 0;
    obj->d.stringdata = string_data;
    obj->d.superdata = &QDBusAbstractInterface::staticMetaObject;
}
Beispiel #2
0
bool SIDPlay::open(const QString &_url, bool tracksOnly)
{
	QString prefix, url, param;
	const bool hasPluginPrefix = Functions::splitPrefixAndUrlIfHasPluginPrefix(_url, &prefix, &url, &param);

	if (tracksOnly == hasPluginPrefix)
		return false;

	int track = 0;
	if (!hasPluginPrefix)
	{
		if (url.startsWith(SIDPlayName "://"))
			return false;
		url = _url;
	}
	else
	{
		if (prefix != SIDPlayName)
			return false;
		bool ok;
		track = param.toInt(&ok);
		if (track < 0 || !ok)
			return false;
	}

	if (Reader::create(url, m_reader))
	{
		const QByteArray data = m_reader->read(m_reader->size());
		m_reader.clear();

		m_tune = new SidTune((const quint8 *)data.data(), data.length());
		if (!m_tune->getStatus())
			return false;

		if (!hasPluginPrefix)
		{
			m_aborted = true;
			m_url = url;
			return true;
		}

		const SidTuneInfo *info = m_tune->getInfo();

		if (track >= (int)info->songs())
			return false;

		m_rs.create(m_sidplay.info().maxsids());
		if (!m_rs.getStatus())
			return false;
		m_rs.filter(true);

#if ((LIBSIDPLAYFP_VERSION_MAJ << 16 | LIBSIDPLAYFP_VERSION_MIN << 8 | LIBSIDPLAYFP_VERSION_LEV) > 0x010800)
		const bool isStereo = info->sidChips() > 1 ? true : false;
#else
		const bool isStereo = info->isStereo();
#endif

		SidConfig cfg;
		cfg.frequency = m_srate;
		cfg.sidEmulation = &m_rs;
		if (isStereo)
			cfg.playback = SidConfig::STEREO;
		cfg.samplingMethod = SidConfig::INTERPOLATE;
		if (!m_sidplay.config(cfg))
			return false;

		m_tune->selectSong(track + 1);

		m_title = getTitle(info, track);
		m_chn = isStereo ? 2 : 1;

		const QString title    = info->infoString(0);
		const QString author   = info->infoString(1);
		const QString released = info->infoString(2);
		if (!title.isEmpty())
			m_tags << qMakePair(QString::number(QMPLAY2_TAG_TITLE), title);
		if (!author.isEmpty())
			m_tags << qMakePair(QString::number(QMPLAY2_TAG_ARTIST), author);
		if (!released.isEmpty())
			m_tags << qMakePair(QString::number(QMPLAY2_TAG_DATE), released);
		m_tags << qMakePair(tr("Track"), QString::number(track + 1));

		streams_info += new StreamInfo(m_srate, m_chn);

		return m_sidplay.load(m_tune);
	}

	return false;
}
QByteArray QProcessResponseThread::GetBody( QByteArray &byStream )
{
    return byStream.right( byStream.length( ) - Protocol::nHeadLength );
}
void ApiServerSetColorTask::startParseSetColorTask(QByteArray buffer)
{
    API_DEBUG_OUT << QString(buffer) << "task thread:" << thread()->currentThreadId();
    bool isReadFail = false;

    // buffer can contains only something like this:
    // 1-34,9,125
    // 2-0,255,0;3-0,255,0;6-0,255,0;

    while (buffer.isEmpty() == false)
    {
        if (isReadFail == true)
        {
            qWarning() << "got it!";
        }

        // Check buffer length, minimum 7 - '2-0,0,0'
        if (buffer.length() < 7)
        {
            API_DEBUG_OUT << "error: buffer.length() < 7";
            isReadFail = true;
            goto end;
        }

        // Read led number
        int ledNumber = LightpackMath::getDigit(buffer[0]); // first char of ledNumber
        int ledNumber2 = LightpackMath::getDigit(buffer[1]); // second char of ledNumber
        if (ledNumber > 0)
        {
            if (buffer[1] == '-')
            {
                buffer.remove(0, 2); // remove "2-"
            }
            else if (ledNumber2 >= 0 && buffer[2] == '-')
            {
                ledNumber = ledNumber * 10 + ledNumber2; // 10,11,12..99
                buffer.remove(0, 3); // remove "10-"
            } else {
                API_DEBUG_OUT << "lednumber fail:" << QString(buffer);
                isReadFail = true;
                goto end;
            }
        } else {
            API_DEBUG_OUT << "isdigit fail:" << QString(buffer);
            isReadFail = true;
            goto end;
        }

        API_DEBUG_OUT << "lednumber-" << ledNumber << "buff-" << QString(buffer);

        if (ledNumber <= 0 || ledNumber > m_numberOfLeds)
        {
            API_DEBUG_OUT << "ledNumber is out of bounds:" << ledNumber;
            isReadFail = true;
            goto end;
        }

        // Convert for using in zero-based arrays
        ledNumber = ledNumber - 1;

        // Read led red, green and blue colors to buffer buffRgb[]
        int indexBuffer = 0;
        int indexRgb = 0;        
        memset(buffRgb, 0, sizeof(buffRgb));

        bool isDigitExpected = true;
        for (indexBuffer = 0; indexBuffer < buffer.length(); indexBuffer++)
        {
            int d = LightpackMath::getDigit(buffer[indexBuffer]);
            if (d < 0)
            {
                if (buffer[indexBuffer] == ';')
                {
                    break;
                }
                else if (buffer[indexBuffer] != ',')
                {
                    API_DEBUG_OUT << "expected comma, buffer:" << QString(buffer) << indexBuffer << buffer[indexBuffer];
                    isReadFail = true;
                    goto end;
                }
                else if (isDigitExpected)
                {
                    API_DEBUG_OUT << "expected digit, buffer:" << QString(buffer) << indexBuffer << buffer[indexBuffer];
                    isReadFail = true;
                    goto end;
                }
                isDigitExpected = true;
                indexRgb++;
            } else {
                buffRgb[indexRgb] *= 10;
                buffRgb[indexRgb] += d;

                isDigitExpected = false;

                if (buffRgb[indexRgb] > 255)
                {
                    API_DEBUG_OUT << "rgb value > 255";
                    isReadFail = true;
                    goto end;
                }
            }
        }

        // Remove read colors
        buffer.remove(0, indexBuffer);

        // Save colors
        m_colors[ledNumber] = qRgb(buffRgb[bRed], buffRgb[bGreen], buffRgb[bBlue]);

        API_DEBUG_OUT << "result color:" << buffRgb[bRed] << buffRgb[bGreen] << buffRgb[bBlue]
                      << "buffer:" << QString(buffer);

        if (buffer[0] == ';')
        {
            // Remove semicolon
            buffer.remove(0, 1);

            API_DEBUG_OUT << "buffer.isEmpty() == " << buffer.isEmpty();
        }
    }

end:
    if (isReadFail)
    {
        API_DEBUG_OUT << "errors while reading buffer";
        emit taskParseSetColorIsSuccess(false);
    } else {
        API_DEBUG_OUT << "read setcolor buffer - ok";
        emit taskParseSetColorDone(m_colors);
        emit taskParseSetColorIsSuccess(true);
    }
}
Beispiel #5
0
void MidiInstrument::read(Xml& xml)
      {
      bool ok;
      int base = 10;
      _nullvalue = -1;
      for (;;) {
            Xml::Token token = xml.parse();
            const QString& tag = xml.s1();
            switch (token) {
                  case Xml::Error:
                  case Xml::End:
                        return;
                  case Xml::TagStart:
                        if (tag == "Patch") {
                              Patch* patch = new Patch;
                              patch->read(xml);
                              if (pg.empty()) {
                                    PatchGroup* p = new PatchGroup;
                                    p->patches.push_back(patch);
                                    pg.push_back(p);
                                    }
                              else
                                    pg[0]->patches.push_back(patch);
                              }
                        else if (tag == "PatchGroup") {
                              PatchGroup* p = new PatchGroup;
                              p->read(xml);
                              pg.push_back(p);
                              }
                        else if (tag == "Controller") {
                              MidiController* mc = new MidiController();
                              mc->read(xml);
                              // Added by Tim. Copied from muse 2.
                              //
                              // HACK: make predefined "Program" controller overloadable
                              //
                              if (mc->name() == "Program") {
                                    for (iMidiController i = _controller->begin(); i != _controller->end(); ++i) {
                                          if (i->second->name() == mc->name()) {
                                                delete i->second;
                                                _controller->erase(i);
                                                break;
                                                }
                                          }
                                    }
                                    
                              _controller->add(mc);
                              }
                        else if (tag == "Drummaps") {
                              readDrummaps(xml);
                              }
                        else if (tag == "Init")
                              readEventList(xml, _midiInit, "Init");
                        else if (tag == "Reset")
                              readEventList(xml, _midiReset, "Reset");
                        else if (tag == "State")
                              readEventList(xml, _midiState, "State");
                        else if (tag == "InitScript") {
                              if (_initScript)
                                    delete _initScript;
                              QByteArray ba = xml.parse1().toLatin1();
                              const char* istr = ba.constData();
                              int len = ba.length() +1;
                              if (len > 1) {
                                    _initScript = new char[len];
                                    memcpy(_initScript, istr, len);
                                    }
                              }
                        else if (tag == "SysEx") {
                              SysEx* se = new SysEx;
                              if(!se->read(xml))
                              {
                                delete se;
                                printf("MidiInstrument::read():SysEx: reading sysex failed\n");
                              }
                              else
                                _sysex.append(se);
                              }
                        else
                              xml.unknown("MidiInstrument");
                        break;
                  case Xml::Attribut:
                        if (tag == "name")
                              setIName(xml.s2());
                        else if(tag == "nullparam") {
                              _nullvalue = xml.s2().toInt(&ok, base);
                        }
                        break;
                  case Xml::TagEnd:
                        if (tag == "MidiInstrument")
                              return;
                  default:
                        break;
                  }
            }
      }
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);
    QTextCodec *big5 = QTextCodec::codecForName("Big5-hkscs");

#if 0
    QFile f("/home/lars/dev/qt-4.0/util/unicode/data/big5-eten.txt");
    f.open(QFile::ReadOnly);

    while (!f.atEnd()) {
        QByteArray line = f.readLine();
        if (line.startsWith("#"))
            continue;
        line.replace("0x", "");
        line.replace("U+", "");
        line.replace("\t", " ");
        line = line.simplified();
        QList<QByteArray> split = line.split(' ');
        bool ok;
        int b5 = split.at(0).toInt(&ok, 16);
        Q_ASSERT(ok);
        int uc = split.at(1).toInt(&ok, 16);
        Q_ASSERT(ok);
        if (b5 < 0x100)
            continue;
#else
    QFile f(":/BIG5");
    f.open(QFile::ReadOnly);

    while (!f.atEnd()) {
        QByteArray line = f.readLine();
        if (line.startsWith("CHARMAP"))
            break;
    }
    QSet<uint> b5_ok;
    QSet<uint> uc_ok;
    QList<Map> b5_to_uc_map;
    QList<Map> uc_to_b5_map;
    while (!f.atEnd()) {
        QByteArray line = f.readLine();
        if (line.startsWith("%"))
            continue;
        if (line.startsWith("END CHARMAP"))
            break;
        line.replace("/x", "");
        line.replace("<U", "");
        line.replace(">", "");
        line.replace("\t", " ");
        line = line.simplified();
        QList<QByteArray> split = line.split(' ');
        bool ok;
        int b5 = split.at(1).toInt(&ok, 16);
        Q_ASSERT(ok);
        int uc = split.at(0).toInt(&ok, 16);
        Q_ASSERT(ok);
        if (b5 < 0x100 || uc > 0xffff)
            continue;
#endif

//         qDebug() << hex << "testing: '" << b5 << "' - '" << uc << "'";
        QByteArray ba;

        ba += (char)(uchar)(b5 >> 8);
        ba += (char)(uchar)(b5 & 0xff);

        QString s = big5->toUnicode(ba);
        Q_ASSERT(s.length() == 1);
        QString s2;
        s2 = QChar(uc);
        ba = big5->fromUnicode(s2);
        Q_ASSERT(ba.length() <= 2);
        int round;
        if (ba.length() == 1)
            round = (int)(uchar)ba[0];
        else
            round = ((int)(uchar)ba[0] << 8) + (int)(uchar)ba[1];
        if (b5 != round)
            uc_to_b5_map += Map(uc, b5);
        else
            b5_ok.insert(b5);

        if (s[0].unicode() != uc)
            b5_to_uc_map += Map(uc, b5);
        else
            uc_ok.insert(uc);
    };

    QList<QByteArray> list;
    foreach(Map m, b5_to_uc_map) {
        if (!uc_ok.contains(m.b5))
            list += QByteArray("    { 0x" + QByteArray::number(m.b5, 16) + ", 0x" + QByteArray::number(m.uc, 16) + " }\n");;
    }
    QByteArray ba;
    qSort(list);
    foreach(QByteArray a, list)
        ba += a;
    qDebug() << "struct B5Map b5_to_uc_map = {\n" << ba + "\n};";

    list = QList<QByteArray>();
    foreach(Map m, uc_to_b5_map)
        if (!b5_ok.contains(m.uc))
            list += QByteArray("    { 0x" + QByteArray::number(m.uc, 16) + ", 0x" + QByteArray::number(m.b5, 16) + " }\n");;
    ba = QByteArray();
    qSort(list);
    foreach(QByteArray a, list)
        ba += a;
    qDebug() << "struct B5Map uc_to_b5_map = {\n" << ba + "\n};";
}
    bool fromString(const QByteArray &str)
    {
        PropList list;
        int at = 0;
        while(1) {
            while (at < str.length() && (str[at] == ',' || str[at] == ' ' || str[at] == '\t'))
                ++at;
            int n = str.indexOf('=', at);
            if(n == -1)
                break;
            QByteArray var, val;
            var = str.mid(at, n-at);
            at = n + 1;
            if(str[at] == '\"') {
                ++at;
                n = str.indexOf('\"', at);
                if(n == -1)
                    break;
                val = str.mid(at, n-at);
                at = n + 1;
            }
            else {
                n = at;
                while (n < str.length() && str[n] != ',' && str[n] != ' ' && str[n] != '\t')
                    ++n;
                val = str.mid(at, n-at);
                at = n;
            }
            Prop prop;
            prop.var = var;
            if (var == "qop" || var == "cipher") {
                int a = 0;
                while (a < val.length()) {
                    while (a < val.length() && (val[a] == ',' || val[a] == ' ' || val[a] == '\t'))
                        ++a;
                    if (a == val.length())
                        break;
                    n = a+1;
                    while (n < val.length() && val[n] != ',' && val[n] != ' ' && val[n] != '\t')
                        ++n;
                    prop.val = val.mid(a, n-a);
                    list.append(prop);
                    a = n+1;
                }
            }
            else {
                prop.val = val;
                list.append(prop);
            }

            if(at >= str.size() - 1 || (str[at] != ',' && str[at] != ' ' && str[at] != '\t'))
                break;
        }

        // integrity check
        if(list.varCount("nonce") != 1)
            return false;
        if(list.varCount("algorithm") != 1)
            return false;
        *this = list;
        return true;
    }
qint64 QProcessBackend::write(const QByteArray& byteArray)
{
    return write(byteArray.data(), byteArray.length());
}
int QPdfEnginePrivate::gradientBrush(const QBrush &b, const QMatrix &matrix, int *gStateObject)
{
    const QGradient *gradient = b.gradient();
    if (!gradient)
        return 0;

    QTransform inv = matrix.inverted();
    QPointF page_rect[4] = { inv.map(QPointF(0, 0)),
                             inv.map(QPointF(width_, 0)),
                             inv.map(QPointF(0, height_)),
                             inv.map(QPointF(width_, height_)) };

    bool opaque = b.isOpaque();

    QByteArray shader;
    QByteArray alphaShader;
    if (gradient->type() == QGradient::LinearGradient) {
        const QLinearGradient *lg = static_cast<const QLinearGradient *>(gradient);
        shader = QPdf::generateLinearGradientShader(lg, page_rect);
        if (!opaque)
            alphaShader = QPdf::generateLinearGradientShader(lg, page_rect, true);
    } else {
        // #############
        return 0;
    }
    int shaderObject = addXrefEntry(-1);
    write(shader);

    QByteArray str;
    QPdf::ByteStream s(&str);
    s << "<<\n"
        "/Type /Pattern\n"
        "/PatternType 2\n"
        "/Shading " << shaderObject << "0 R\n"
        "/Matrix ["
      << matrix.m11()
      << matrix.m12()
      << matrix.m21()
      << matrix.m22()
      << matrix.dx()
      << matrix.dy() << "]\n";
    s << ">>\n"
        "endobj\n";

    int patternObj = addXrefEntry(-1);
    write(str);
    currentPage->patterns.append(patternObj);

    if (!opaque) {
        bool ca = true;
        QGradientStops stops = gradient->stops();
        int a = stops.at(0).second.alpha();
        for (int i = 1; i < stops.size(); ++i) {
            if (stops.at(i).second.alpha() != a) {
                ca = false;
                break;
            }
        }
        if (ca) {
            *gStateObject = addConstantAlphaObject(stops.at(0).second.alpha());
        } else {
            int alphaShaderObject = addXrefEntry(-1);
            write(alphaShader);

            QByteArray content;
            QPdf::ByteStream c(&content);
            c << "/Shader" << alphaShaderObject << "sh\n";

            QByteArray form;
            QPdf::ByteStream f(&form);
            f << "<<\n"
                "/Type /XObject\n"
                "/Subtype /Form\n"
                "/BBox [0 0 " << width_ << height_ << "]\n"
                "/Group <</S /Transparency >>\n"
                "/Resources <<\n"
                "/Shading << /Shader" << alphaShaderObject << alphaShaderObject << "0 R >>\n"
                ">>\n";

            f << "/Length " << content.length() << "\n"
                ">>\n"
                "stream\n"
              << content
              << "endstream\n"
                "endobj\n";

            int softMaskFormObject = addXrefEntry(-1);
            write(form);
            *gStateObject = addXrefEntry(-1);
            xprintf("<< /SMask << /S /Alpha /G %d 0 R >> >>\n"
                    "endobj\n", softMaskFormObject);
            currentPage->graphicStates.append(*gStateObject);
        }
    }

    return patternObj;
}
Beispiel #10
0
/*!
    Converts \a a from the encoding of this codec to Unicode, and
    returns the result in a QString.
*/
QString QTextCodec::toUnicode(const QByteArray& a) const
{
    return convertToUnicode(a.constData(), a.length(), 0);
}
Beispiel #11
0
/*!
    \overload

    Converts the bytes in the byte array specified by \a ba to Unicode
    and returns the result.
*/
QString QTextDecoder::toUnicode(const QByteArray &ba)
{
    return c->toUnicode(ba.constData(), ba.length(), &state);
}
Beispiel #12
0
bool CThumbIndex::UpdateAbstract(const WIZABSTRACT &abstractNew, const CString& type)
{
    if(!m_dbThumb.IsOpened()) {
        TOLOG(_T("Fault error: thumb database does not opened"));
        return false;
    }

    QByteArray data;
    if (abstractNew.image.width() > 0 && abstractNew.image.height() > 0)
    {
        int width = abstractNew.image.width();
        int height = abstractNew.image.height();

        // process thumbnail
        QImage img;
        if (width >= 120 && height >= 120) {
            if (width > height) {
                img = abstractNew.image.scaledToHeight(120, Qt::SmoothTransformation);
                img = img.copy((img.width() - 120)/2, 0, 120, 120);
            } else {
                img = abstractNew.image.scaledToWidth(120, Qt::SmoothTransformation);
                img = img.copy(0, (img.height() - 120)/2, 120, 120);
            }
        } else if (width > 120 || height > 120) {
            img = abstractNew.image.scaled(120, 120, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        } else {
            img = abstractNew.image;
        }

        if (img.isNull())
        {
            TOLOG(_T("Faile to scale image to abstract"));
            return false;
        }
        //
        QBuffer buffer(&data);
        buffer.open(QIODevice::WriteOnly);
        if (!img.save(&buffer, "JPG"))
        {
            TOLOG(_T("Faile to save abstract image data to buffer"));
            return false;
        }
        buffer.close();
    }


    WIZABSTRACT abstractOld;
    if (AbstractFromGUID(abstractNew.guid ,abstractOld, type))
    {
        CString whereField = CString("ABSTRACT_GUID=%1 and ABSTRACT_TYPE=%2")
                             .arg(STR2SQL(abstractNew.guid))
                             .arg(STR2SQL(type));

        CString strSql = CString("update %1 set ABSTRACT_TEXT=%2 where %3")
                         .arg(TABLE_NAME_ABSTRACT)
                         .arg(STR2SQL(abstractNew.text))
                         .arg(whereField);

        try
        {
            m_dbThumb.execDML(strSql);
            m_dbThumb.updateBlob(TABLE_NAME_ABSTRACT, "ABSTRACT_IMAGE", (const unsigned char*)data.constData() , data.length(), whereField);
            return true;
        }
        catch (const CppSQLite3Exception& e)
        {
            TOLOG(e.errorMessage());
            TOLOG(strSql);
            return false;
        }
        catch (...)
        {
            TOLOG("Unknown exception while update document");
            return false;
        }
    }
    else
    {
        CString strSql = CString("insert into %1 (%2) values(%3, %4, %5, ?)")
                         .arg(TABLE_NAME_ABSTRACT)
                         .arg(FIELD_LIST_ABSTRACT)
                         .arg(STR2SQL(abstractNew.guid))
                         .arg(STR2SQL(type))
                         .arg(STR2SQL(abstractNew.text));

        try
        {
            m_dbThumb.insertBlob(strSql, (const unsigned char*)data.constData() , data.length());
            return true;
        }
        catch (const CppSQLite3Exception& e)
        {
            TOLOG(e.errorMessage());
            TOLOG(strSql);
            return false;
        }
        catch (...)
        {
            TOLOG("Unknown exception while update document");
            return false;
        }
    }

    return true;
}
ClientSocketOpt::ClientSocketOpt(QObject *parent) : QObject(parent)
{
    timerid = -1;
    recvCounts = 0;
    socket = nullptr;
    socketThread = new QThread;
    socketThread->setObjectName("client socket thread");
    this->moveToThread(socketThread);

    connect(socketThread, &QThread::finished, this, [=] () {
        this->deleteLater();
        socketThread->deleteLater();
    });

    connect(this, &ClientSocketOpt::connectHost,
            this, [=] (QString ip, quint16 port) {
        socket = new QTcpSocket(this);
        connect(socket, &QTcpSocket::connected,
                this, [=] () {
            // connected
            emit connected();
        });
        socket->connectToHost(ip, port);
        if (!socket->waitForConnected())
        {
            emit recvInformation(cn("接收终止"));
            emit disconnected();
            socketThread->quit();
            return;
        }


        QFile *file = new QFile(this);
        TcpDataDeal *deal = new TcpDataDeal(this);
        MessageDataDeal *msg = new MessageDataDeal(this);
        connect(deal, &TcpDataDeal::fullFrameData,
                msg, &MessageDataDeal::ParserFrameData);

        connect(msg, &MessageDataDeal::recvMessageData,
                this, [=] (MessageData data) {
            if (data.datatype() != FileSendType &&
                data.datatype() != commonStr)
                return;
            if (data.datatype() == commonStr)
            {
                MessageCharData *charconent = dynamic_cast<MessageCharData*>(data.content());
                if (charconent && charconent->type() == FileInfo)
                {
                    QString strinfo = QString::fromLocal8Bit(charconent->content());
                    emit recvInformation(strinfo);
                }
                return;
            }
            // write file
            FileDataContent *content = dynamic_cast<FileDataContent*>(data.content());
            if (!content)
                return;
            FileDataContent::FileHead *head = content->sendInfo();
            FileDataContent::FileNameHead *namehead = content->fileName();
            emit recvProgress(head->totalProgress >= 100 ? 99 : head->totalProgress, head->currentProgress / 100.0);
            QString filename = namehead->name.replace(namehead->path, savePath + "/");
            QFileInfo info(filename);
            emit recvInformation(cn("正在接收 %1").arg(info.fileName()));
            QDir dir(info.absolutePath());
            if (!dir.exists())
                dir.mkpath(info.absolutePath());
            if (file->fileName() != filename)
            {
                file->close();
                if (info.exists())
                {
                    QString dt = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
                    filename = info.absolutePath() + "/" +
                            info.bundleName() + dt + "." + info.suffix();
                }
                file->setFileName(filename);
            }
            if (!file->isOpen())
            {
                file->open(QIODevice::WriteOnly | QIODevice::Append);
            }
            if (file->isWritable())
            {
                file->write(content->data(), head->fileCurrentSize);
                if (head->currentProgress == 100)
                    file->close();
            }
            if (socketThread->isInterruptionRequested())
            {
                emit recvInformation(cn("接收终止"));
                file->close();
                socket->disconnectFromHost();
                socket->abort();
                socketThread->quit();
            }
            if (head->currentProgress == 100 && head->totalProgress == 100)
            {
                file->close();
                emit recvProgress(100, 1);
                emit recvInformation(cn("接收完成"));
                emit disconnected();
                socket->disconnectFromHost();
                socket->abort();
                socketThread->quit();
            }
        });

        connect(socket, &QTcpSocket::disconnected,
                this, [=] () {
            // disconnected
        });
        connect(socket, static_cast<void(QTcpSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::error),
                this, [=] () {
            emit recvInformation(cn("接收终止"));
            emit disconnected();
            socketThread->quit();
        });
        connect(this, &ClientSocketOpt::senddata,
                this, [=] (QByteArray ba) {
            if (socket->state() != QAbstractSocket::ConnectedState)
                return;
            socket->write(ba);
            socket->waitForBytesWritten();
            socket->flush();
        });
        connect(socket, &QTcpSocket::readyRead,
                this, [=] () {
            // read data
            QByteArray ba = socket->readAll();
            recvCounts += ba.length();
            NetworkData nd(ba.data(), ba.length());
            deal->slotPosData(nd);
        });

        timerid = startTimer(1000);
    });
    socketThread->start();
}
Beispiel #14
0
void QCmdParser::ParseDataDomain( QByteArray &data, QString& strInfo, qint8& nIndex )
{
    // data.length( ) >= 4

    qint32 nDomainLen = 4;

    if ( nDomainLen > data.length( ) ) {
        return;
    }

    qint32 nDI = data[ 0 ];
    nDI |= ( data[ 1 ] << 8 );
    nDI |= ( data[ 2 ] << 16 );
    nDI |= ( data[ 3 ] << 24 );

    data.remove( 0, nDomainLen );
    nDomainLen = data.length( );

    strInfo = "";

    switch ( nDI ) {
    case 0x04000300 :
        nIndex = 0;
        break;

    case 0x0400030C : // ƵÉÁ¹âÃô¿ØÖÆ
        GeLedtIlluminance( data, strInfo );
        nIndex = 1;
        break;

    case 0x04000301 : // ζÈ
        GetLedTemperature( data, strInfo );
        nIndex = 3;
        break;

    case 0x04000302 : // µÆ¹¤×÷״̬£¨00 =ƵÉÁ£»01=ÉÁ¹â£©Ä£Ê½
        GetLedWorkState( data, strInfo );
        nIndex = 4;
        break;

    case 0x04000303 : // ƵÉÁ´¥·¢·½Ê½£¨00=ÉÏÉýÑØ´¥·¢£»01=ϽµÑØ´¥·¢£»02=¸úËæģʽ£©Í¬²½
        GetLedFreqTriggerMode( data, strInfo );
        nIndex = 5;
        break;

    case 0x04000304 : // Êä³öÂö¿í0£¨°Ù·Ö±ÈÏÔʾ£©ÆµÉÁʱ¼ä
        GetLedFreqTime( data, strInfo );
        nIndex = 7;
        break;

    case 0x04000305 : // Êä³öÂö¿í1£¨°Ù·Ö±ÈÏÔʾ£©ÉÁ¹âʱ¼ä
        GetLedFlashTime( data, strInfo );
        nIndex = 8;
        break;

    case 0x04000306 : // Êä³öÂö¿í2£¨°Ù·Ö±ÈÏÔʾ£©ÆµÉÁÁÁ¶È
        GetLedFreqBrightness( data, strInfo );
        nIndex = 9;
        break;

    case 0x04000307 : // Êä³öÂö¿í3£¨°Ù·Ö±ÈÏÔʾ£©ÉÁ¹âÁÁ¶È
        GetLedFlashBrightness( data, strInfo );
        nIndex = 10;
        break;

    case 0x04000308 : // ƵÉÁƵÂÊ
        GetLedFrequency( data, strInfo );
        nIndex = 13;
        break;

    case 0x04000309 : // LEDµÆ¹¤×÷µçѹ
        GetLedWorkVoltage( data, strInfo );
        nIndex = 14;
        break;

    case 0x0400030A : // Íⲿ´¥·¢ÐźÅ״̬£¨00= Õý³££»01 = Òì³££©
        GetLedExternalTriggerSignalState( data, strInfo );
        nIndex = 15;
        break;

    case 0x0400030B : // ÉÁ¹â´¥·¢·½Ê½£¨00=ÉÏÉýÑØ´¥·¢£»01=ϽµÑØ´¥·¢£»02=¸úËæģʽ£©Í¬²½
        GetLedFlashTriggerMode( data, strInfo );
        nIndex = 6;
        break;

    case 0x0400030E : // ƵÉÁ¹âÃô·§Öµ
        GetThreshold( data, strInfo );
        nIndex = 11;
        break;

    case 0x0400030F : // ÉÁ¹â¹âÃô·§Öµ
        GetThreshold( data, strInfo );
        nIndex = 12;
        break;

    case 0x0400030D : // ÉÁ¹â¹âÃô¿ØÖÆ
        GeLedtIlluminance( data, strInfo );
        nIndex = 2;
        break;

    case 0x04000310 : // ֡Ƶ¿ØÖÆ
        GetFrameFreqControl( data, strInfo );
        nIndex = 16;
        break;
    }
}
bool HelloForeignWindowApp::createForeignWindow(const QString &group, const QString id, int x,
        int y, int width, int height)
{
    QByteArray groupArr = group.toAscii();
    QByteArray idArr = id.toAscii();

    // Window source rectangle.
    mRect[0] = 0;
    mRect[1] = 0;
    mRect[2] = width;
    mRect[3] = height;

    // You must create a context before you create a window.
    if (screen_create_context(&mScreenCtx, SCREEN_APPLICATION_CONTEXT) != 0) {
        return false;
    }

    // Create a child window of the current window group, join the window group and set
    // a window id.
    if (screen_create_window_type(&mScreenWindow, mScreenCtx, SCREEN_CHILD_WINDOW) != 0) {
        return false;
    }
    if (screen_join_window_group(mScreenWindow, groupArr.constData()) != 0) {
        return false;
    }
    if (screen_set_window_property_cv(mScreenWindow, SCREEN_PROPERTY_ID_STRING, idArr.length(),
            idArr.constData()) != 0) {
        return false;
    }

    // In this application we will render to a pixmap buffer and then blit that to
    // the window, we set the usage to native (default is read and write but we do not need that here).
    int usage = SCREEN_USAGE_NATIVE;
    if (screen_set_window_property_iv(mScreenWindow, SCREEN_PROPERTY_USAGE, &usage) != 0) {
        return false;
    }

    // The window size is specified in QML so we need to set up the buffer size to
    // correspond to that, the default size would be the full screen.
    if (screen_set_window_property_iv(mScreenWindow, SCREEN_PROPERTY_BUFFER_SIZE, mRect + 2) != 0) {
        return false;
    }
    if (screen_set_window_property_iv(mScreenWindow, SCREEN_PROPERTY_SOURCE_SIZE, mRect + 2) != 0) {
        return false;
    }

    // Use negative Z order so that the window appears under the main window.
    // This is needed by the ForeignWindow functionality.
    int z = -5;
    if (screen_set_window_property_iv(mScreenWindow, SCREEN_PROPERTY_ZORDER, &z) != 0) {
        return false;
    }

    // Set the window position on screen.
    int pos[2] = { x, y };
    if (screen_set_window_property_iv(mScreenWindow, SCREEN_PROPERTY_POSITION, pos) != 0) {
        return false;
    }

    // Finally create the window buffers, in this application we will only use one buffer.
    if (screen_create_window_buffers(mScreenWindow, 1) != 0) {
        return false;
    }

    // In this sample we use a pixmap to render to, a pixmap. This allows us to have
    // full control of exactly which pixels we choose to push to the screen.
    screen_pixmap_t screen_pix;
    if (screen_create_pixmap(&screen_pix, mScreenCtx) != 0) {
        return false;
    }

    // A combination of write and native usage is necessary to blit the pixmap to screen.
    usage = SCREEN_USAGE_WRITE | SCREEN_USAGE_NATIVE;
    if(screen_set_pixmap_property_iv(screen_pix, SCREEN_PROPERTY_USAGE, &usage) != 0) {
        return false;
    }

    // Set the width and height of the buffer to correspond to the one we specified in QML.
    mSize[0] = width;
    mSize[1] = height;
    if (screen_set_pixmap_property_iv(screen_pix, SCREEN_PROPERTY_BUFFER_SIZE, mSize) != 0) {
        return false;
    }

    // Create the pixmap buffer and get a reference to it for rendering in the doNoise function.
    if (screen_create_pixmap_buffer(screen_pix) != 0) {
        return false;
    }
    if (screen_get_pixmap_property_pv(screen_pix, SCREEN_PROPERTY_RENDER_BUFFERS,
            (void **) &mScreenPixelBuffer) != 0) {
        return false;
    }

    // We get the stride (the number of bytes between pixels on different rows), its used
    // later on when we perform the rendering to the pixmap buffer.
    if (screen_get_buffer_property_iv(mScreenPixelBuffer, SCREEN_PROPERTY_STRIDE, &mStride) != 0) {
        return false;
    }

    return true;
}
int QPdfEnginePrivate::addBrushPattern(const QTransform &m, bool *specifyColor, int *gStateObject)
{
    int paintType = 2; // Uncolored tiling
    int w = 8;
    int h = 8;

    *specifyColor = true;
    *gStateObject = 0;

    QTransform matrix = m;
    matrix.translate(brushOrigin.x(), brushOrigin.y());
    matrix = matrix * pageMatrix();
    //qDebug() << brushOrigin << matrix;

    Qt::BrushStyle style = brush.style();
    if (style == Qt::LinearGradientPattern) {// && style <= Qt::ConicalGradientPattern) {
#ifdef USE_NATIVE_GRADIENTS
        *specifyColor = false;
        return gradientBrush(b, matrix, gStateObject);
#else
        return 0;
#endif
    }

    if ((!brush.isOpaque() && brush.style() < Qt::LinearGradientPattern) || opacity != 1.0)
        *gStateObject = addConstantAlphaObject(qRound(brush.color().alpha() * opacity),
                                               qRound(pen.color().alpha() * opacity));

    int imageObject = -1;
    QByteArray pattern = QPdf::patternForBrush(brush);
    if (pattern.isEmpty()) {
        if (brush.style() != Qt::TexturePattern)
            return 0;
        QImage image = brush.texture().toImage();
        bool bitmap = true;
        imageObject = addImage(image, &bitmap, qt_pixmap_id(brush.texture()));
        if (imageObject != -1) {
            QImage::Format f = image.format();
            if (f != QImage::Format_MonoLSB && f != QImage::Format_Mono) {
                paintType = 1; // Colored tiling
                *specifyColor = false;
            }
            w = image.width();
            h = image.height();
            QTransform m(w, 0, 0, -h, 0, h);
            QPdf::ByteStream s(&pattern);
            s << QPdf::generateMatrix(m);
            s << "/Im" << imageObject << " Do\n";
        }
    }

    QByteArray str;
    QPdf::ByteStream s(&str);
    s << "<<\n"
        "/Type /Pattern\n"
        "/PatternType 1\n"
        "/PaintType " << paintType << "\n"
        "/TilingType 1\n"
        "/BBox [0 0 " << w << h << "]\n"
        "/XStep " << w << "\n"
        "/YStep " << h << "\n"
        "/Matrix ["
      << matrix.m11()
      << matrix.m12()
      << matrix.m21()
      << matrix.m22()
      << matrix.dx()
      << matrix.dy() << "]\n"
        "/Resources \n<< "; // open resource tree
    if (imageObject > 0) {
        s << "/XObject << /Im" << imageObject << ' ' << imageObject << "0 R >> ";
    }
    s << ">>\n"
        "/Length " << pattern.length() << "\n"
        ">>\n"
        "stream\n"
      << pattern
      << "endstream\n"
        "endobj\n";

    int patternObj = addXrefEntry(-1);
    write(str);
    currentPage->patterns.append(patternObj);
    return patternObj;
}
Beispiel #17
0
void
TomahawkApp::init()
{
    if ( arguments().contains( "--help" ) || arguments().contains( "-h" ) )
    {
        printHelp();
        ::exit( 0 );
    }

    qDebug() << "TomahawkApp thread:" << thread();
    Logger::setupLogfile();
    qsrand( QTime( 0, 0, 0 ).secsTo( QTime::currentTime() ) );

    tLog() << "Starting Tomahawk...";

#ifdef ENABLE_HEADLESS
    m_headless = true;
#else
    m_mainwindow = 0;
    m_headless = arguments().contains( "--headless" );
    setWindowIcon( QIcon( RESPATH "icons/tomahawk-icon-128x128.png" ) );
    setQuitOnLastWindowClosed( false );

    QFont f = APP->font();
    f.setPixelSize( HeaderLabel::defaultFontSize() );
    QFontMetrics fm( f );
    TomahawkUtils::setHeaderHeight( fm.height() + 8 );
#endif

    TomahawkSettings* s = TomahawkSettings::instance();

    tDebug( LOGINFO ) << "Setting NAM.";
    // Cause the creation of the nam, but don't need to address it directly, so prevent warning
    Q_UNUSED( TomahawkUtils::nam() );

    m_audioEngine = QWeakPointer<AudioEngine>( new AudioEngine );
    m_scanManager = QWeakPointer<ScanManager>( new ScanManager( this ) );

    // init pipeline and resolver factories
    new Pipeline( this );

#ifndef ENABLE_HEADLESS
    Pipeline::instance()->addExternalResolverFactory( boost::bind( &QtScriptResolver::factory, _1 ) );
    Pipeline::instance()->addExternalResolverFactory( boost::bind( &ScriptResolver::factory, _1 ) );

    new ActionCollection( this );
    connect( ActionCollection::instance()->getAction( "quit" ), SIGNAL( triggered() ), SLOT( quit() ), Qt::UniqueConnection );
#endif

    m_servent = QWeakPointer<Servent>( new Servent( this ) );
    connect( m_servent.data(), SIGNAL( ready() ), SLOT( initSIP() ) );

    tDebug() << "Init Database.";
    initDatabase();

    QByteArray magic = QByteArray::fromBase64( enApiSecret );
    QByteArray wand = QByteArray::fromBase64( QCoreApplication::applicationName().toLatin1() );
    int length = magic.length(), n2 = wand.length();
    for ( int i=0; i<length; i++ ) magic[i] = magic[i] ^ wand[i%n2];
    Echonest::Config::instance()->setAPIKey( magic );

#ifndef ENABLE_HEADLESS
    tDebug() << "Init Echonest Factory.";
    GeneratorFactory::registerFactory( "echonest", new EchonestFactory );
#endif
    tDebug() << "Init Database Factory.";
    GeneratorFactory::registerFactory( "database", new DatabaseFactory );

    // Register shortcut handler for this platform
#ifdef Q_WS_MAC
    m_shortcutHandler = QWeakPointer<Tomahawk::ShortcutHandler>( new MacShortcutHandler( this ) );
    Tomahawk::setShortcutHandler( static_cast<MacShortcutHandler*>( m_shortcutHandler.data() ) );

    Tomahawk::setApplicationHandler( this );
    increaseMaxFileDescriptors();
#endif

    // Connect up shortcuts
    if ( !m_shortcutHandler.isNull() )
    {
        connect( m_shortcutHandler.data(), SIGNAL( playPause() ), m_audioEngine.data(), SLOT( playPause() ) );
        connect( m_shortcutHandler.data(), SIGNAL( pause() ), m_audioEngine.data(), SLOT( pause() ) );
        connect( m_shortcutHandler.data(), SIGNAL( stop() ), m_audioEngine.data(), SLOT( stop() ) );
        connect( m_shortcutHandler.data(), SIGNAL( previous() ), m_audioEngine.data(), SLOT( previous() ) );
        connect( m_shortcutHandler.data(), SIGNAL( next() ), m_audioEngine.data(), SLOT( next() ) );
        connect( m_shortcutHandler.data(), SIGNAL( volumeUp() ), m_audioEngine.data(), SLOT( raiseVolume() ) );
        connect( m_shortcutHandler.data(), SIGNAL( volumeDown() ), m_audioEngine.data(), SLOT( lowerVolume() ) );
        connect( m_shortcutHandler.data(), SIGNAL( mute() ), m_audioEngine.data(), SLOT( mute() ) );
    }

    tDebug() << "Init InfoSystem.";
    m_infoSystem = QWeakPointer<Tomahawk::InfoSystem::InfoSystem>( new Tomahawk::InfoSystem::InfoSystem( this ) );

    Echonest::Config::instance()->setNetworkAccessManager( TomahawkUtils::nam() );
#ifndef ENABLE_HEADLESS
    EchonestGenerator::setupCatalogs();


    if ( !m_headless )
    {
        tDebug() << "Init MainWindow.";
        m_mainwindow = new TomahawkWindow();
        m_mainwindow->setWindowTitle( "Tomahawk" );
        m_mainwindow->setObjectName( "TH_Main_Window" );
        if ( !arguments().contains( "--hide" ) )
        {
            m_mainwindow->show();
        }
    }
#endif

    tDebug() << "Init Local Collection.";
    initLocalCollection();
    tDebug() << "Init Pipeline.";
    initPipeline();

#ifdef LIBATTICA_FOUND
#ifndef ENABLE_HEADLESS
    // load remote list of resolvers able to be installed
    AtticaManager::instance();
#endif
#endif

    if ( arguments().contains( "--http" ) || TomahawkSettings::instance()->value( "network/http", true ).toBool() )
    {
        initHTTP();
    }

#ifndef ENABLE_HEADLESS
    if ( !s->hasScannerPaths() )
    {
        m_mainwindow->showSettingsDialog();
    }
#endif

#ifdef LIBLASTFM_FOUND
    tDebug() << "Init Scrobbler.";
    m_scrobbler = new Scrobbler( this );
#endif

    if ( arguments().contains( "--filescan" ) )
    {
        m_scanManager.data()->runScan( true );
    }

    // Set up echonest catalog synchronizer
    Tomahawk::EchonestCatalogSynchronizer::instance();

#ifndef ENABLE_HEADLESS
    // Make sure to init GAM in the gui thread
    GlobalActionManager::instance();

    // check if our spotify playlist api server is up and running, and enable spotify playlist drops if so
    QNetworkReply* r = TomahawkUtils::nam()->get( QNetworkRequest( QUrl( SPOTIFY_PLAYLIST_API_URL "/playlist/test" ) ) );
    connect( r, SIGNAL( finished() ), this, SLOT( spotifyApiCheckFinished() ) );
#endif

#ifdef Q_WS_MAC
    // Make sure to do this after main window is inited
    Tomahawk::enableFullscreen();
#endif
}
static QNetworkInterfacePrivate *findInterface(int socket, QList<QNetworkInterfacePrivate *> &interfaces,
                                               struct ifreq &req)
{
    QNetworkInterfacePrivate *iface = 0;
    int ifindex = 0;

#ifndef QT_NO_IPV6IFNAME
    // Get the interface index
    ifindex = if_nametoindex(req.ifr_name);

    // find the interface data
    QList<QNetworkInterfacePrivate *>::Iterator if_it = interfaces.begin();
    for ( ; if_it != interfaces.end(); ++if_it)
        if ((*if_it)->index == ifindex) {
            // existing interface
            iface = *if_it;
            break;
        }
#else
    // Search by name
    QList<QNetworkInterfacePrivate *>::Iterator if_it = interfaces.begin();
    for ( ; if_it != interfaces.end(); ++if_it)
        if ((*if_it)->name == QLatin1String(req.ifr_name)) {
            // existing interface
            iface = *if_it;
            break;
        }
#endif

    if (!iface) {
        // new interface, create data:
        iface = new QNetworkInterfacePrivate;
        iface->index = ifindex;
        interfaces << iface;

#ifdef SIOCGIFNAME
        // Get the canonical name
        QByteArray oldName = req.ifr_name;
        if (qt_safe_ioctl(socket, SIOCGIFNAME, &req) >= 0) {
            iface->name = QString::fromLatin1(req.ifr_name);

            // reset the name:
            memcpy(req.ifr_name, oldName, qMin<int>(oldName.length() + 1, sizeof(req.ifr_name) - 1));
        } else
#endif
        {
            // use this name anyways
            iface->name = QString::fromLatin1(req.ifr_name);
        }

        // Get interface flags
        if (qt_safe_ioctl(socket, SIOCGIFFLAGS, &req) >= 0) {
            iface->flags = convertFlags(req.ifr_flags);
        }

#ifdef SIOCGIFHWADDR
        // Get the HW address
        if (qt_safe_ioctl(socket, SIOCGIFHWADDR, &req) >= 0) {
            uchar *addr = (uchar *)req.ifr_addr.sa_data;
            iface->hardwareAddress = iface->makeHwAddress(6, addr);
        }
#endif
    }

    return iface;
}
    virtual void tryAgain() {
        // All exits of the method must emit the ready signal
        // so all exits go through a goto ready;
        if(step == 0) {
            out_mech = mechanism_;

#ifdef SIMPLESASL_PLAIN
            // PLAIN
            if (out_mech == "PLAIN") {
                // First, check if we have everything
                if(need.user || need.pass) {
                    qWarning("simplesasl.cpp: Did not receive necessary auth parameters");
                    result_ = Error;
                    goto ready;
                }
                if(!have.user)
                    need.user = true;
                if(!have.pass)
                    need.pass = true;
                if(need.user || need.pass) {
                    result_ = Params;
                    goto ready;
                }

                // Continue with authentication
                QByteArray plain;
                if (!authz.isEmpty())
                    plain += authz.toUtf8();
                plain += '\0' + user.toUtf8() + '\0' + pass.toByteArray();
                out_buf.resize(plain.length());
                memcpy(out_buf.data(), plain.data(), out_buf.size());
            }
#endif
            ++step;
            if (out_mech == "PLAIN")
                result_ = Success;
            else
                result_ = Continue;
        }
        else if(step == 1) {
            // if we still need params, then the app has failed us!
            if(need.user || need.authzid || need.pass || need.realm) {
                qWarning("simplesasl.cpp: Did not receive necessary auth parameters");
                result_ = Error;
                goto ready;
            }
            // see if some params are needed
            if(!have.user)
                need.user = true;
            //if(!have.authzid)
            //	need.authzid = true;
            if(!have.pass)
                need.pass = true;
            if(need.user || need.authzid || need.pass) {
                result_ = Params;
                goto ready;
            }

            // get props
            QByteArray cs(in_buf);
            PropList in;
            if(!in.fromString(cs)) {
                authCondition_ = QCA::SASL::BadProtocol;
                result_ = Error;
                goto ready;
            }
            //qDebug() << (QString("simplesasl.cpp: IN: %1").arg(QString(in.toString())));

            // make a cnonce
            QByteArray a(32,'\0');
            for(int n = 0; n < (int)a.size(); ++n)
                a[n] = (char)(256.0*rand()/(RAND_MAX+1.0));
            QByteArray cnonce = QCA::Base64().arrayToString(a).toLatin1();

            // make other variables
            if (realm.isEmpty())
                realm = QString::fromUtf8(in.get("realm"));
            QByteArray nonce = in.get("nonce");
            QByteArray nc = "00000001";
            QByteArray uri = service.toUtf8() + '/' + host.toUtf8();
            QByteArray qop = "auth";

            // build 'response'
            QByteArray X = user.toUtf8() + ':' + realm.toUtf8() + ':' + pass.toByteArray();
            QByteArray Y = QCA::Hash("md5").hash(X).toByteArray();
            QByteArray tmp = ':' + nonce + ':' + cnonce;
            if (!authz.isEmpty())
                tmp += ':' + authz.toUtf8();
            //qDebug() << (QString(tmp));

            QByteArray A1(Y + tmp);
            QByteArray A2 = QByteArray("AUTHENTICATE:") + uri;
            QByteArray HA1 = QCA::Hash("md5").hashToString(A1).toLatin1();
            QByteArray HA2 = QCA::Hash("md5").hashToString(A2).toLatin1();
            QByteArray KD = HA1 + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + HA2;
            QByteArray Z = QCA::Hash("md5").hashToString(KD).toLatin1();

            //qDebug() << (QString("simplesasl.cpp: A1 = %1").arg(QString(A1)).toAscii());
            //qDebug() << (QString("simplesasl.cpp: A2 = %1").arg(QString(A2)).toAscii());
            //qDebug() << (QString("simplesasl.cpp: KD = %1").arg(QString(KD)).toAscii());

            // build output
            PropList out;
            out.set("username", user.toUtf8());
            if (!realm.isEmpty())
                out.set("realm", realm.toUtf8());
            out.set("nonce", nonce);
            out.set("cnonce", cnonce);
            out.set("nc", nc);
            //out.set("serv-type", service.utf8());
            //out.set("host", host.utf8());
            out.set("digest-uri", uri);
            out.set("qop", qop);
            out.set("response", Z);
            out.set("charset", "utf-8");
            if (!authz.isEmpty())
                out.set("authzid", authz.toUtf8());
            QByteArray s(out.toString());
            //qDebug() << (QString("OUT: %1").arg(QString(out.toString())));

            // done
            out_buf.resize(s.length());
            memcpy(out_buf.data(), s.data(), out_buf.size());
            ++step;
            result_ = Continue;
        }
        /*		else if (step == 2) {
        			out_buf.resize(0);
        			result_ = Continue;
        			++step;
        		}*/
        else {
            out_buf.resize(0);
            result_ = Success;
        }
ready:
        QMetaObject::invokeMethod(this, "resultsReady", Qt::QueuedConnection);
    }
Beispiel #20
0
void QHexEditPrivate::remove(int index, int len)
{
    if (len > 0)
    {
        if (len == 1)
        {
            if (_overwriteMode)
            {
                QUndoCommand *charCommand = new CharCommand(&_xData, CharCommand::replace, index, char(0));
                _undoStack->push(charCommand);
                emit dataChanged();
            }
            else
            {
                QUndoCommand *charCommand = new CharCommand(&_xData, CharCommand::remove, index, char(0));
                _undoStack->push(charCommand);
                emit dataChanged();
            }
        }
        else
        {
            QByteArray ba = QByteArray(len, char(0));
            if (_overwriteMode)
            {
                QUndoCommand *arrayCommand = new ArrayCommand(&_xData, ArrayCommand::replace, index, ba, ba.length());
                _undoStack->push(arrayCommand);
                emit dataChanged();
            }
            else
            {
                QUndoCommand *arrayCommand= new ArrayCommand(&_xData, ArrayCommand::remove, index, ba, len);
                _undoStack->push(arrayCommand);
                emit dataChanged();
            }
        }
    }
}
void MythSocket::WriteStringListReal(const QStringList *list, bool *ret)
{
    if (list->empty())
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            "WriteStringList: Error, invalid string list.");
        *ret = false;
        return;
    }

    if (m_tcpSocket->state() != QAbstractSocket::ConnectedState)
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            "WriteStringList: Error, called with unconnected socket.");
        *ret = false;
        return;
    }

    QString str = list->join("[]:[]");
    if (str.isEmpty())
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            "WriteStringList: Error, joined null string.");
        *ret = false;
        return;
    }

    QByteArray utf8 = str.toUtf8();
    int size = utf8.length();
    int written = 0;
    int written_since_timer_restart = 0;

    QByteArray payload;
    payload = payload.setNum(size);
    payload += "        ";
    payload.truncate(8);
    payload += utf8;
    size = payload.length();

    if (VERBOSE_LEVEL_CHECK(VB_NETWORK, LOG_INFO))
    {
        QString msg = QString("write -> %1 %2")
            .arg(m_tcpSocket->socketDescriptor(), 2).arg(payload.data());

        if (logLevel < LOG_DEBUG && msg.length() > 88)
        {
            msg.truncate(85);
            msg += "...";
        }
        LOG(VB_NETWORK, LOG_INFO, LOC + msg);
    }

    MythTimer timer; timer.start();
    unsigned int errorcount = 0;
    while (size > 0)
    {
        if (m_tcpSocket->state() != QAbstractSocket::ConnectedState)
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                "WriteStringList: Error, socket went unconnected." +
                QString("\n\t\t\tWe wrote %1 of %2 bytes with %3 errors")
                    .arg(written).arg(written+size).arg(errorcount) +
                    QString("\n\t\t\tstarts with: %1").arg(to_sample(payload)));
            *ret = false;
            return;
        }

        int temp = m_tcpSocket->write(payload.data() + written, size);
        if (temp > 0)
        {
            written += temp;
            written_since_timer_restart += temp;
            size -= temp;
            if ((timer.elapsed() > 500) && written_since_timer_restart != 0)
            {
                timer.restart();
                written_since_timer_restart = 0;
            }
        }
        else if (temp <= 0)
        {
            errorcount++;
            if (timer.elapsed() > 1000)
            {
                LOG(VB_GENERAL, LOG_ERR, LOC + "WriteStringList: Error, " +
                    QString("No data written on write (%1 errors)")
                        .arg(errorcount) +
                    QString("\n\t\t\tstarts with: %1")
                    .arg(to_sample(payload)));
                *ret = false;
                return;
            }
            usleep(1000);
        }
    }

    m_tcpSocket->flush();

    *ret = true;
    return;
}
Beispiel #22
0
void QHexEditPrivate::replace(int index, const QByteArray & ba)
{
    QUndoCommand *arrayCommand= new ArrayCommand(&_xData, ArrayCommand::replace, index, ba, ba.length());
    _undoStack->push(arrayCommand);
    emit dataChanged();
}
void ApplicationUI::pad(QByteArray & in) {
	int padLength = 16 - (in.length() % 16);
	for (int i = 0; i < padLength; ++i) {
		in.append((char) padLength);
	}
}
Beispiel #24
0
void QHexEditPrivate::keyPressEvent(QKeyEvent *event)
{
    int charX = (_cursorX - _xPosHex) / _charWidth;
    int posX = (charX / 3) * 2 + (charX % 3);
    int posBa = (_cursorY / _charHeight) * BYTES_PER_LINE + posX / 2;


/*****************************************************************************/
/* Cursor movements */
/*****************************************************************************/

    if (event->matches(QKeySequence::MoveToNextChar))
    {
        setCursorPos(_cursorPosition + 1);
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToPreviousChar))
    {
        setCursorPos(_cursorPosition - 1);
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToEndOfLine))
    {
        setCursorPos(_cursorPosition | (2 * BYTES_PER_LINE -1));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToStartOfLine))
    {
        setCursorPos(_cursorPosition - (_cursorPosition % (2 * BYTES_PER_LINE)));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToPreviousLine))
    {
        setCursorPos(_cursorPosition - (2 * BYTES_PER_LINE));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToNextLine))
    {
        setCursorPos(_cursorPosition + (2 * BYTES_PER_LINE));
        resetSelection(_cursorPosition);
    }

    if (event->matches(QKeySequence::MoveToNextPage))
    {
        setCursorPos(_cursorPosition + (((_scrollArea->viewport()->height() / _charHeight) - 1) * 2 * BYTES_PER_LINE));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToPreviousPage))
    {
        setCursorPos(_cursorPosition - (((_scrollArea->viewport()->height() / _charHeight) - 1) * 2 * BYTES_PER_LINE));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToEndOfDocument))
    {
        setCursorPos(_xData.size() * 2);
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToStartOfDocument))
    {
        setCursorPos(0);
        resetSelection(_cursorPosition);
    }

/*****************************************************************************/
/* Select commands */
/*****************************************************************************/
    if (event->matches(QKeySequence::SelectAll))
    {
        resetSelection(0);
        setSelection(2*_xData.size() + 1);
    }
    if (event->matches(QKeySequence::SelectNextChar))
    {
        int pos = _cursorPosition + 1;
        setCursorPos(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectPreviousChar))
    {
        int pos = _cursorPosition - 1;
        setSelection(pos);
        setCursorPos(pos);
    }
    if (event->matches(QKeySequence::SelectEndOfLine))
    {
        int pos = _cursorPosition - (_cursorPosition % (2 * BYTES_PER_LINE)) + (2 * BYTES_PER_LINE);
        setCursorPos(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectStartOfLine))
    {
        int pos = _cursorPosition - (_cursorPosition % (2 * BYTES_PER_LINE));
        setCursorPos(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectPreviousLine))
    {
        int pos = _cursorPosition - (2 * BYTES_PER_LINE);
        setCursorPos(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectNextLine))
    {
        int pos = _cursorPosition + (2 * BYTES_PER_LINE);
        setCursorPos(pos);
        setSelection(pos);
    }

    if (event->matches(QKeySequence::SelectNextPage))
    {
        int pos = _cursorPosition + (((_scrollArea->viewport()->height() / _charHeight) - 1) * 2 * BYTES_PER_LINE);
        setCursorPos(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectPreviousPage))
    {
        int pos = _cursorPosition - (((_scrollArea->viewport()->height() / _charHeight) - 1) * 2 * BYTES_PER_LINE);
        setCursorPos(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectEndOfDocument))
    {
        int pos = _xData.size() * 2;
        setCursorPos(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectStartOfDocument))
    {
        int pos = 0;
        setCursorPos(pos);
        setSelection(pos);
    }

/*****************************************************************************/
/* Edit Commands */
/*****************************************************************************/
if (!_readOnly)
{
    /* Hex input */
        int key = int(event->text()[0].toAscii());
        if ((key>='0' && key<='9') || (key>='a' && key <= 'f'))
        {
            if (getSelectionBegin() != getSelectionEnd())
            {
                posBa = getSelectionBegin();
                remove(posBa, getSelectionEnd() - posBa);
                setCursorPos(2*posBa);
                resetSelection(2*posBa);
            }

            // If insert mode, then insert a byte
            if (_overwriteMode == false)
                if ((charX % 3) == 0)
                {
                    insert(posBa, char(0));
                }

            // Change content
            if (_xData.size() > 0)
            {
                QByteArray hexValue = _xData.data().mid(posBa, 1).toHex();
                if ((charX % 3) == 0)
                    hexValue[0] = key;
                else
                    hexValue[1] = key;

                replace(posBa, QByteArray().fromHex(hexValue)[0]);

                setCursorPos(_cursorPosition + 1);
                resetSelection(_cursorPosition);
            }
        }

        /* Cut & Paste */
        if (event->matches(QKeySequence::Cut))
        {
            QString result = QString();
            for (int idx = getSelectionBegin(); idx < getSelectionEnd(); idx++)
            {
                result += _xData.data().mid(idx, 1).toHex() + " ";
                if ((idx % 16) == 15)
                    result.append("\n");
            }
            remove(getSelectionBegin(), getSelectionEnd() - getSelectionBegin());
            QClipboard *clipboard = QApplication::clipboard();
            clipboard->setText(result);
            setCursorPos(getSelectionBegin());
            resetSelection(getSelectionBegin());
        }

        if (event->matches(QKeySequence::Paste))
        {
            QClipboard *clipboard = QApplication::clipboard();
            QByteArray ba = QByteArray().fromHex(clipboard->text().toLatin1());
            insert(_cursorPosition / 2, ba);
            setCursorPos(_cursorPosition + 2 * ba.length());
            resetSelection(getSelectionBegin());
        }


        /* Delete char */
        if (event->matches(QKeySequence::Delete))
        {
            if (getSelectionBegin() != getSelectionEnd())
            {
                posBa = getSelectionBegin();
                remove(posBa, getSelectionEnd() - posBa);
                setCursorPos(2*posBa);
                resetSelection(2*posBa);
            }
            else
            {
                if (_overwriteMode)
                    replace(posBa, char(0));
                else
                    remove(posBa, 1);
            }
        }

        /* Backspace */
        if ((event->key() == Qt::Key_Backspace) && (event->modifiers() == Qt::NoModifier))
            {
                if (getSelectionBegin() != getSelectionEnd())
                {
                    posBa = getSelectionBegin();
                    remove(posBa, getSelectionEnd() - posBa);
                    setCursorPos(2*posBa);
                    resetSelection(2*posBa);
                }
                else
                {
                    if (posBa > 0)
                    {
                        if (_overwriteMode)
                            replace(posBa - 1, char(0));
                        else
                            remove(posBa - 1, 1);
                        setCursorPos(_cursorPosition - 2);
                    }
                }
            }

        /* undo */
        if (event->matches(QKeySequence::Undo))
        {
            undo();
        }

        /* redo */
        if (event->matches(QKeySequence::Redo))
        {
            redo();
        }

    }

    if (event->matches(QKeySequence::Copy))
    {
        QString result = QString();
        for (int idx = getSelectionBegin(); idx < getSelectionEnd(); idx++)
        {
            result += _xData.data().mid(idx, 1).toHex() + " ";
            if ((idx % 16) == 15)
                result.append('\n');
        }
        QClipboard *clipboard = QApplication::clipboard();
        clipboard->setText(result);
    }

    // Switch between insert/overwrite mode
    if ((event->key() == Qt::Key_Insert) && (event->modifiers() == Qt::NoModifier))
    {
        _overwriteMode = !_overwriteMode;
        setCursorPos(_cursorPosition);
        overwriteModeChanged(_overwriteMode);
    }

    _scrollArea->ensureVisible(_cursorX, _cursorY + _charHeight/2, 3, _charHeight/2 + 2);
    adjust();
}
// API Candidate?
void DumpRenderTreeSupportQt::setAlternateHtml(QWebFrameAdapter* adapter, const QString& html, const QUrl& baseUrl, const QUrl& failingUrl)
{
    KURL kurl(baseUrl);
    WebCore::Frame* coreFrame = adapter->frame;
    WebCore::ResourceRequest request(kurl);
    const QByteArray utf8 = html.toUtf8();
    WTF::RefPtr<WebCore::SharedBuffer> data = WebCore::SharedBuffer::create(utf8.constData(), utf8.length());
    WebCore::SubstituteData substituteData(data, WTF::String("text/html"), WTF::String("utf-8"), failingUrl);
    coreFrame->loader()->load(WebCore::FrameLoadRequest(coreFrame, request, substituteData));
}
QNetworkReply *	NetworkAccessManager::createRequest(Operation op, const QNetworkRequest & req, QIODevice * outgoingData)
{
    QByteArray data;
    QBuffer* buffer = 0;

    // cache the content first
    if (outgoingData) {
        buffer = new QBuffer(this);
        data = outgoingData->readAll();
        buffer->setData(data);
    }

    if (d->ShouldLogRequestResponse) {
        qDebug() << "Queueing Request: " << req.url().toString();
    }

    QNetworkReply* reply = QNetworkAccessManager::createRequest(op, req, buffer);
    reply->ignoreSslErrors();

    if (outgoingData) {
        qDebug() << "Request Details# op=" << op << ", url=" <<  req.url().toString() << ", data("<<data.length() <<")=" << data;
        if (d->removeRequestInfo(reply)) {
            qWarning() << "Same request aleady cached. So going to remove reference to old one.";
        }
        d->DataMap.insert(reply, new RequestInfo(op, data, buffer));
    }

    return reply;
}
Beispiel #27
0
QgsWkbPtr::QgsWkbPtr( QByteArray &wkb )
{
    mP = reinterpret_cast<unsigned char*>( wkb.data() );
    mStart = mP;
    mEnd = mP + wkb.length();
}
void FollowStreamDialog::addText(QString text, gboolean is_from_server, guint32 packet_num)
{
    if (save_as_ == true)
    {
        size_t nwritten;
        int FileDescriptor = file_.handle();
        int fd_new = ws_dup(FileDescriptor);
        if (fd_new == -1)
            return;
        FILE* fh = ws_fdopen(fd_new, "wb");
        if (show_type_ == SHOW_RAW) {
            QByteArray binstream = QByteArray::fromHex(text.toUtf8());
            nwritten = fwrite(binstream.constData(), binstream.length(), 1, fh);
        } else {
            nwritten = fwrite(text.toUtf8().constData(), text.length(), 1, fh);
        }
        fclose(fh);
        if ((int)nwritten != text.length()) {
#if 0
            report_an_error_maybe();
#endif
        }
        return;
    }

    if (truncated_) {
        return;
    }

    int char_count = ui->teStreamContent->document()->characterCount();
    if (char_count + text.length() > max_document_length_) {
        text.truncate(max_document_length_ - char_count);
        truncated_ = true;
    }

    setUpdatesEnabled(false);
    int cur_pos = ui->teStreamContent->verticalScrollBar()->value();
    ui->teStreamContent->moveCursor(QTextCursor::End);
    QTextCharFormat tcf = ui->teStreamContent->currentCharFormat();
    if (is_from_server) {
        tcf.setForeground(ColorUtils::fromColorT(prefs.st_server_fg));
        tcf.setBackground(ColorUtils::fromColorT(prefs.st_server_bg));
    } else {
        tcf.setForeground(ColorUtils::fromColorT(prefs.st_client_fg));
        tcf.setBackground(ColorUtils::fromColorT(prefs.st_client_bg));
    }
    ui->teStreamContent->setCurrentCharFormat(tcf);

    ui->teStreamContent->insertPlainText(text);
    text_pos_to_packet_[ui->teStreamContent->textCursor().anchor()] = packet_num;

    if (truncated_) {
        tcf = ui->teStreamContent->currentCharFormat();
        tcf.setBackground(palette().window().color());
        tcf.setForeground(palette().windowText().color());
        ui->teStreamContent->insertPlainText("\n" + tr("[Stream output truncated]"));
        ui->teStreamContent->moveCursor(QTextCursor::End);
    } else {
        ui->teStreamContent->verticalScrollBar()->setValue(cur_pos);
    }
    setUpdatesEnabled(true);
}
Beispiel #29
0
QHash<QByteArray, QByteArray> QAuthenticatorPrivate::parseDigestAuthenticationChallenge(const QByteArray &challenge)
{
    QHash<QByteArray, QByteArray> options;
    // parse the challenge
    const char *d = challenge.constData();
    const char *end = d + challenge.length();
    while (d < end) {
        while (d < end && (*d == ' ' || *d == '\n' || *d == '\r'))
            ++d;
        const char *start = d;
        while (d < end && *d != '=')
            ++d;
        QByteArray key = QByteArray(start, d - start);
        ++d;
        if (d >= end)
            break;
        bool quote = (*d == '"');
        if (quote)
            ++d;
        if (d >= end)
            break;
        start = d;
        QByteArray value;
        while (d < end) {
            bool backslash = false;
            if (*d == '\\' && d < end - 1) {
                ++d;
                backslash = true;
            }
            if (!backslash) {
                if (quote) {
                    if (*d == '"')
                        break;
                } else {
                    if (*d == ',')
                        break;
                }
            }
            value += *d;
            ++d;
        }
        while (d < end && *d != ',')
            ++d;
        ++d;
        options[key] = value;
    }

    QByteArray qop = options.value("qop");
    if (!qop.isEmpty()) {
        QList<QByteArray> qopoptions = qop.split(',');
        if (!qopoptions.contains("auth"))
            return QHash<QByteArray, QByteArray>();
        // #### can't do auth-int currently
//         if (qop.contains("auth-int"))
//             qop = "auth-int";
//         else if (qop.contains("auth"))
//             qop = "auth";
//         else
//             qop = QByteArray();
        options["qop"] = "auth";
    }

    return options;
}
void QDBusMetaObjectGenerator::parseMethods()
{
    //
    // TODO:
    //  Add cloned methods when the remote object has return types
    //

    QDBusIntrospection::Methods::ConstIterator method_it = data->methods.constBegin();
    QDBusIntrospection::Methods::ConstIterator method_end = data->methods.constEnd();
    for ( ; method_it != method_end; ++method_it) {
        const QDBusIntrospection::Method &m = *method_it;
        Method mm;

        mm.name = m.name.toLatin1();
        QByteArray prototype = mm.name;
        prototype += '(';

        bool ok = true;

        // build the input argument list
        for (int i = 0; i < m.inputArgs.count(); ++i) {
            const QDBusIntrospection::Argument &arg = m.inputArgs.at(i);

            Type type = findType(arg.type.toLatin1(), m.annotations, "In", i);
            if (type.id == QVariant::Invalid) {
                ok = false;
                break;
            }

            mm.inputSignature += arg.type.toLatin1();
            mm.inputTypes.append(type.id);

            mm.parameters.append(arg.name.toLatin1());
            mm.parameters.append(',');
            
            prototype.append(type.name);
            prototype.append(',');
        }
        if (!ok) continue;

        // build the output argument list:
        for (int i = 0; i < m.outputArgs.count(); ++i) {
            const QDBusIntrospection::Argument &arg = m.outputArgs.at(i);

            Type type = findType(arg.type.toLatin1(), m.annotations, "Out", i);
            if (type.id == QVariant::Invalid) {
                ok = false;
                break;
            }

            mm.outputSignature += arg.type.toLatin1();
            mm.outputTypes.append(type.id);

            if (i == 0) {
                // return value
                mm.typeName = type.name;
            } else {
                // non-const ref parameter
                mm.parameters.append(arg.name.toLatin1());
                mm.parameters.append(',');

                prototype.append(type.name);
                prototype.append("&,");
            }
        }
        if (!ok) continue;

        // convert the last commas:
        if (!mm.parameters.isEmpty()) {
            mm.parameters.truncate(mm.parameters.length() - 1);
            prototype[prototype.length() - 1] = ')';
        } else {
            prototype.append(')');
        }

        // check the async tag
        if (m.annotations.value(QLatin1String(ANNOTATION_NO_WAIT)) == QLatin1String("true"))
            mm.tag = "Q_NOREPLY";

        // meta method flags
        mm.flags = AccessPublic | MethodSlot | MethodScriptable;

        // add
        methods.insert(QMetaObject::normalizedSignature(prototype), mm);
    }
}