Esempio n. 1
0
ParsedLabel parseLabel(const QByteArray& label)
{
    ParsedLabel ret;
    int functionStart = 0;
    int functionEnd = label.length();
    if (label.startsWith("0x")) {
        int colonPos = label.indexOf(": ");
        if (colonPos != -1) {
            ret.address = label.left(colonPos);
            functionStart = colonPos + 2;
        }
    }
    if (label.endsWith(')')) {
        int locationPos = label.lastIndexOf(" (");
        if (locationPos != -1) {
            ret.location = label.mid(locationPos + 2, label.length() - locationPos - 3);
            functionEnd = locationPos;
        }
    }
    ret.function = label.mid(functionStart, functionEnd - functionStart);
    return ret;
}
Esempio n. 2
0
void ProppatchJob::start()
{
    if (_properties.isEmpty()) {
        qCWarning(lcProppatchJob) << "Proppatch with no properties!";
    }
    QNetworkRequest req;

    QByteArray propStr;
    QMapIterator<QByteArray, QByteArray> it(_properties);
    while (it.hasNext()) {
        it.next();
        QByteArray keyName = it.key();
        QByteArray keyNs;
        if (keyName.contains(':')) {
            int colIdx = keyName.lastIndexOf(":");
            keyNs = keyName.left(colIdx);
            keyName = keyName.mid(colIdx + 1);
        }

        propStr += "    <" + keyName;
        if (!keyNs.isEmpty()) {
            propStr += " xmlns=\"" + keyNs + "\" ";
        }
        propStr += ">";
        propStr += it.value();
        propStr += "</" + keyName + ">\n";
    }
    QByteArray xml = "<?xml version=\"1.0\" ?>\n"
                     "<d:propertyupdate xmlns:d=\"DAV:\">\n"
                     "  <d:set><d:prop>\n"
        + propStr + "  </d:prop></d:set>\n"
                    "</d:propertyupdate>\n";

    QBuffer *buf = new QBuffer(this);
    buf->setData(xml);
    buf->open(QIODevice::ReadOnly);
    sendRequest("PROPPATCH", makeDavUrl(path()), req, buf);
    AbstractNetworkJob::start();
}
Esempio n. 3
0
static QString qtCoreFromOtool(const QString &path)
{
  QProcess proc;
  proc.setProcessChannelMode(QProcess::SeparateChannels);
  proc.setReadChannel(QProcess::StandardOutput);
  proc.start("otool", QStringList() << "-L" << path);
  proc.waitForFinished();

  forever {
    const QByteArray line = proc.readLine();
    if (line.isEmpty())
      break;

    if (ProbeABIDetector::containsQtCore(line)) {
      const int pos = line.lastIndexOf(" (");
      if (pos <= 0)
        continue;
      return QString::fromLocal8Bit(line.left(pos).trimmed());
    }
  }

  return QString();
}
void GdbRemoteServerEngine::callTargetRemote()
{
    QByteArray rawChannel = startParameters().remoteChannel.toLatin1();
    QByteArray channel = rawChannel;

    // Don't touch channels with explicitly set protocols.
    if (!channel.startsWith("tcp:") && !channel.startsWith("udp:")
            && !channel.startsWith("file:") && channel.contains(':'))
    {
        // "Fix" the IPv6 case with host names without '['...']'
        if (!channel.startsWith('[') && channel.count(':') >= 2) {
            channel.insert(0, '[');
            channel.insert(channel.lastIndexOf(':'), ']');
        }
        channel = "tcp:" + channel;
    }

    if (m_isQnxGdb)
        postCommand("target qnx " + channel, CB(handleTargetQnx));
    else if (m_isMulti)
        postCommand("target extended-remote " + m_serverChannel, CB(handleTargetExtendedRemote));
    else
        postCommand("target remote " + channel, CB(handleTargetRemote), 10);
}
Esempio n. 5
0
static QString qtCoreFromLdd(const QString &path)
{
    QProcess proc;
    proc.setProcessChannelMode(QProcess::SeparateChannels);
    proc.setReadChannel(QProcess::StandardOutput);
    proc.start(QStringLiteral("ldd"), QStringList() << path);
    proc.waitForFinished();

    forever {
        const QByteArray line = proc.readLine();
        if (line.isEmpty())
            break;

        if (ProbeABIDetector::containsQtCore(line)) {
            const int begin = line.indexOf("=> ");
            const int end = line.lastIndexOf(" (");
            if (begin <= 0 || end <= 0 || end <= begin)
                continue;
            return QString::fromLocal8Bit(line.mid(begin + 3, end - begin - 3).trimmed());
        }
    }

    return QString();
}
Esempio n. 6
0
void HTTPConnection::readRequest() {
    if (!_socket->canReadLine()) {
        return;
    }
    // parse out the method and resource
    QByteArray line = _socket->readLine().trimmed();
    if (line.startsWith("HEAD")) {
        _requestOperation = QNetworkAccessManager::HeadOperation;

    } else if (line.startsWith("GET")) {
        _requestOperation = QNetworkAccessManager::GetOperation;

    } else if (line.startsWith("PUT")) {
        _requestOperation = QNetworkAccessManager::PutOperation;

    } else if (line.startsWith("POST")) {
        _requestOperation = QNetworkAccessManager::PostOperation;

    } else if (line.startsWith("DELETE")) {
        _requestOperation = QNetworkAccessManager::DeleteOperation;

    } else {
        qWarning() << "Unrecognized HTTP operation." << _address << line;
        respond("400 Bad Request", "Unrecognized operation.");
        return;
    }
    int idx = line.indexOf(' ') + 1;
    _requestUrl.setUrl(line.mid(idx, line.lastIndexOf(' ') - idx));

    // switch to reading the header
    _socket->disconnect(this, SLOT(readRequest()));
    connect(_socket, SIGNAL(readyRead()), SLOT(readHeaders()));

    // read any headers immediately available
    readHeaders();
}
Esempio n. 7
0
void SysTray::ubuntu_unity_hack_getFinished(int exit_code) 
{
    QProcess* get = qobject_cast<QProcess*>(sender());
    if (!get)
      return;

    get->deleteLater();

    if (exit_code != 0) {
      // Probably not running in Unity.
      return;
    }

    QByteArray whitelist = get->readAllStandardOutput();

    Debug::debug() << "Unity whitelist is" << whitelist;

    int index = whitelist.lastIndexOf(']');
    if (index == -1 || whitelist.contains("'yarock'"))
      return;

    whitelist = whitelist.left(index) + QString(", 'yarock'").toUtf8() +
                whitelist.mid(index);

    Debug::debug() << "Setting unity whitelist to" << whitelist;

    QProcess* set = new QProcess(this);
    
    connect(set, SIGNAL(finished(int)), set, SLOT(deleteLater()));
    set->start(kGSettingsFileName, QStringList()
             << "set" << kUnityPanel << kUnitySystrayWhitelist << whitelist);

    Debug::debug() << "Yarock has added itself to the Unity system tray" <<
                      "whitelist, but this won't take effect until the next time" <<
                      "you log out and log back in.";
}
Esempio n. 8
0
void Generator::generateCode()
{
    bool isQt = (cdef->classname == "Qt");
    bool isQObject = (cdef->classname == "QObject");
    bool isConstructible = !cdef->constructorList.isEmpty();

//
// build the data array
//
    int i = 0;


    // filter out undeclared enumerators and sets
    {
        QList<EnumDef> enumList;
        for (i = 0; i < cdef->enumList.count(); ++i) {
            EnumDef def = cdef->enumList.at(i);
            if (cdef->enumDeclarations.contains(def.name)) {
                enumList += def;
            }
            QByteArray alias = cdef->flagAliases.value(def.name);
            if (cdef->enumDeclarations.contains(alias)) {
                def.name = alias;
                enumList += def;
            }
        }
        cdef->enumList = enumList;
    }


    QByteArray qualifiedClassNameIdentifier = cdef->qualified;
    qualifiedClassNameIdentifier.replace(':', '_');

    int index = 12;
    fprintf(out, "static const uint qt_meta_data_%s[] = {\n", qualifiedClassNameIdentifier.constData());
    fprintf(out, "\n // content:\n");
    fprintf(out, "    %4d,       // revision\n", 2);
    fprintf(out, "    %4d,       // classname\n", strreg(cdef->qualified));
    fprintf(out, "    %4d, %4d, // classinfo\n", cdef->classInfoList.count(), cdef->classInfoList.count() ? index : 0);
    index += cdef->classInfoList.count() * 2;

    int methodCount = cdef->signalList.count() + cdef->slotList.count() + cdef->methodList.count();
    fprintf(out, "    %4d, %4d, // methods\n", methodCount, methodCount ? index : 0);
    index += methodCount * 5;
    fprintf(out, "    %4d, %4d, // properties\n", cdef->propertyList.count(), cdef->propertyList.count() ? index : 0);
    index += cdef->propertyList.count() * 3;
    if(cdef->notifyableProperties)
        index += cdef->propertyList.count();
    fprintf(out, "    %4d, %4d, // enums/sets\n", cdef->enumList.count(), cdef->enumList.count() ? index : 0);

    int enumsIndex = index;
    for (i = 0; i < cdef->enumList.count(); ++i)
        index += 4 + (cdef->enumList.at(i).values.count() * 2);
    fprintf(out, "    %4d, %4d, // constructors\n", isConstructible ? cdef->constructorList.count() : 0,
            isConstructible ? index : 0);

//
// Build classinfo array
//
    generateClassInfos();

//
// Build signals array first, otherwise the signal indices would be wrong
//
    generateFunctions(cdef->signalList, "signal", MethodSignal);

//
// Build slots array
//
    generateFunctions(cdef->slotList, "slot", MethodSlot);

//
// Build method array
//
    generateFunctions(cdef->methodList, "method", MethodMethod);


//
// Build property array
//
    generateProperties();

//
// Build enums array
//
    generateEnums(enumsIndex);

//
// Build constructors array
//
    if (isConstructible)
        generateFunctions(cdef->constructorList, "constructor", MethodConstructor);

//
// Terminate data array
//
    fprintf(out, "\n       0        // eod\n};\n\n");

//
// Build stringdata array
//
    fprintf(out, "static const char qt_meta_stringdata_%s[] = {\n", qualifiedClassNameIdentifier.constData());
    fprintf(out, "    \"");
    int col = 0;
    int len = 0;
    for (i = 0; i < strings.size(); ++i) {
        QByteArray s = strings.at(i);
        len = s.length();
        if (col && col + len >= 72) {
            fprintf(out, "\"\n    \"");
            col = 0;
        } else if (len && s.at(0) >= '0' && s.at(0) <= '9') {
            fprintf(out, "\"\"");
            len += 2;
        }
        int idx = 0;
        while (idx < s.length()) {
            if (idx > 0) {
                col = 0;
                fprintf(out, "\"\n    \"");
            }
            int spanLen = qMin(70, s.length() - idx);
            // don't cut escape sequences at the end of a line
            int backSlashPos = s.lastIndexOf('\\', idx + spanLen - 1);
            if (backSlashPos >= idx) {
                int escapeLen = lengthOfEscapeSequence(s, backSlashPos);
                spanLen = qBound(spanLen, backSlashPos + escapeLen - idx, s.length() - idx);
            }
            fwrite(s.constData() + idx, 1, spanLen, out);
            idx += spanLen;
            col += spanLen;
        }

        fputs("\\0", out);
        col += len + 2;
    }
    fprintf(out, "\"\n};\n\n");


//
// Generate internal qt_static_metacall() function
//
    if (isConstructible)
        generateStaticMetacall(qualifiedClassNameIdentifier);

//
// Build extra array
//
    QList<QByteArray> extraList;
    for (int i = 0; i < cdef->propertyList.count(); ++i) {
        const PropertyDef &p = cdef->propertyList.at(i);
        if (!isVariantType(p.type) && !metaTypes.contains(p.type)) {
            int s = p.type.lastIndexOf("::");
            if (s > 0) {
                QByteArray scope = p.type.left(s);
                if (scope != "Qt" && scope != cdef->classname && !extraList.contains(scope))
                    extraList += scope;
            }
        }
    }
    if (!extraList.isEmpty()) {
        fprintf(out, "static const QMetaObject *qt_meta_extradata_%s[] = {\n    ", qualifiedClassNameIdentifier.constData());
        for (int i = 0; i < extraList.count(); ++i) {
            if (i)
                fprintf(out, ",\n    ");
            fprintf(out, "    &%s::staticMetaObject", extraList.at(i).constData());
        }
        fprintf(out, ",0\n};\n\n");
    }

    if (isConstructible || !extraList.isEmpty()) {
        fprintf(out, "static const QMetaObjectExtraData qt_meta_extradata2_%s = {\n    ",
                qualifiedClassNameIdentifier.constData());
        if (extraList.isEmpty())
            fprintf(out, "0, ");
        else
            fprintf(out, "qt_meta_extradata_%s, ", qualifiedClassNameIdentifier.constData());
        if (!isConstructible)
            fprintf(out, "0");
        else
            fprintf(out, "%s_qt_static_metacall", qualifiedClassNameIdentifier.constData());
        fprintf(out, " \n};\n\n");
    }

//
// Finally create and initialize the static meta object
//

    if (isQt)
        fprintf(out, "const QMetaObject QObject::staticQtMetaObject = {\n");
    else
        fprintf(out, "const QMetaObject %s::staticMetaObject = {\n", cdef->qualified.constData());

    if (isQObject)
        fprintf(out, "    { 0, ");
    else if (cdef->superclassList.size())
        fprintf(out, "    { &%s::staticMetaObject, ", purestSuperClass.constData());
    else
        fprintf(out, "    { 0, ");
    fprintf(out, "qt_meta_stringdata_%s,\n      qt_meta_data_%s, ",
             qualifiedClassNameIdentifier.constData(), qualifiedClassNameIdentifier.constData());
    if (!isConstructible && extraList.isEmpty())
        fprintf(out, "0 }\n");
    else
        fprintf(out, "&qt_meta_extradata2_%s }\n", qualifiedClassNameIdentifier.constData());
    fprintf(out, "};\n");

    if (isQt || !cdef->hasQObject)
        return;

    fprintf(out, "\nconst QMetaObject *%s::metaObject() const\n{\n    return &staticMetaObject;\n}\n",
            cdef->qualified.constData());
//
// Generate smart cast function
//
    fprintf(out, "\nvoid *%s::qt_metacast(const char *_clname)\n{\n", cdef->qualified.constData());
    fprintf(out, "    if (!_clname) return 0;\n");
    fprintf(out, "    if (!strcmp(_clname, qt_meta_stringdata_%s))\n"
                  "        return static_cast<void*>(const_cast< %s*>(this));\n",
            qualifiedClassNameIdentifier.constData(), cdef->classname.constData());
    for (int i = 1; i < cdef->superclassList.size(); ++i) { // for all superclasses but the first one
        if (cdef->superclassList.at(i).second == FunctionDef::Private)
            continue;
        const char *cname = cdef->superclassList.at(i).first;
        fprintf(out, "    if (!strcmp(_clname, \"%s\"))\n        return static_cast< %s*>(const_cast< %s*>(this));\n",
                cname, cname, cdef->classname.constData());
    }
    for (int i = 0; i < cdef->interfaceList.size(); ++i) {
        const QList<ClassDef::Interface> &iface = cdef->interfaceList.at(i);
        for (int j = 0; j < iface.size(); ++j) {
            fprintf(out, "    if (!strcmp(_clname, %s))\n        return ", iface.at(j).interfaceId.constData());
            for (int k = j; k >= 0; --k)
                fprintf(out, "static_cast< %s*>(", iface.at(k).className.constData());
            fprintf(out, "const_cast< %s*>(this)%s;\n",
                    cdef->classname.constData(), QByteArray(j+1, ')').constData());
        }
    }
    if (!purestSuperClass.isEmpty() && !isQObject) {
        QByteArray superClass = purestSuperClass;
        // workaround for VC6
        if (superClass.contains("::")) {
            fprintf(out, "    typedef %s QMocSuperClass;\n", superClass.constData());
            superClass = "QMocSuperClass";
        }
        fprintf(out, "    return %s::qt_metacast(_clname);\n", superClass.constData());
    } else {
        fprintf(out, "    return 0;\n");
    }
    fprintf(out, "}\n");

//
// Generate internal qt_metacall()  function
//
    generateMetacall();

//
// Generate internal signal functions
//
    for (int signalindex = 0; signalindex < cdef->signalList.size(); ++signalindex)
        generateSignal(&cdef->signalList[signalindex], signalindex);
}
Esempio n. 9
0
void CgiProtocol::get( const KUrl& url )
{
  kDebug(7124) << "CgiProtocol::get()";
  kDebug(7124) << " URL: " << url.url();
#if 0
  kDebug(7124) << " Path: " << url.path();
  kDebug(7124) << " Query: " << url.query();
  kDebug(7124) << " Protocol: " << url.protocol();
  kDebug(7124) << " Filename: " << url.filename();
#endif
  QByteArray protocol = "SERVER_PROTOCOL=HTTP";
  putenv( protocol.data() );

  QByteArray requestMethod = "REQUEST_METHOD=GET";
  putenv( requestMethod.data() );

  QByteArray query = url.query().mid( 1 ).toLocal8Bit();
  query.prepend( "QUERY_STRING=" );
  putenv( query.data() );

  QString path = url.path();

  QString file;

  int pos = path.lastIndexOf('/');
  if ( pos >= 0 ) file = path.mid( pos + 1 );
  else file = path;

  QString cmd;

  bool stripHeader = false;
  bool forwardFile = true;

  QStringList::ConstIterator it;
  for( it = mCgiPaths.constBegin(); it != mCgiPaths.constEnd(); ++it ) {
    cmd = *it;
    if ( !(*it).endsWith('/') )
        cmd += '/';
    cmd += file;
    if ( KStandardDirs::exists( cmd ) ) {
      forwardFile = false;
      stripHeader = true;
      break;
    }
  }

  FILE *fd;

  if ( forwardFile ) {
    kDebug(7124) << "Forwarding to '" << path << "'";

    QByteArray filepath = QFile::encodeName( path );

    fd = fopen( filepath.data(), "r" );

    if ( !fd ) {
      kDebug(7124) << "Error opening '" << filepath << "'";
      error(KIO::ERR_CANNOT_OPEN_FOR_READING, path);
      return;
    }
  } else {
    kDebug(7124) << "Cmd: " << cmd;

    fd = popen( QFile::encodeName(KShell::quoteArg( cmd )).data(), "r" );

    if ( !fd ) {
      kDebug(7124) << "Error running '" << cmd << "'";
      error( KIO::ERR_CANNOT_OPEN_FOR_READING, cmd );
      return;
    }
  }

  char buffer[ 4090 ];

  while ( !feof( fd ) )
  {
    int n = fread( buffer, 1, 2048, fd );

    if ( n == -1 )
    {
      // ERROR
      if ( forwardFile ) {
        fclose( fd );
      } else {
        pclose( fd );
      }
      return;
    }

    buffer[n] = 0;

    if ( stripHeader ) {
      QByteArray output = buffer; // this assumes buffer is text and not binary
      int colon = output.indexOf( ':' );
      int newline = output.indexOf( '\n' );
      int semicolon = output.lastIndexOf( ';', newline );
      int end;
      if ( semicolon < 0 ) end = newline;
      else end = semicolon;

#if 0
      kDebug(7124) << "  colon: " << colon;
      kDebug(7124) << "  newline: " << newline;
      kDebug(7124) << "  semicolon: " << semicolon;
      kDebug(7124) << "  end: " << end;
#endif

      // Set the charset meta data if one exists (BR# 241364).
      if (end == semicolon) {
          const int assignOp = output.indexOf('=', semicolon + 1);
          if (assignOp != -1) {
              const QByteArray charset (output.mid(assignOp+1, newline- assignOp -1).trimmed());
              kDebug(7124) << "Charset:" << charset;
              setMetaData(QLatin1String("charset"), charset.toLower());
          }
      }

      QByteArray contentType = output.mid( colon + 1, end - colon - 1 );

      contentType = contentType.trimmed().toLower();

      kDebug(7124) << "ContentType: '" << contentType << "'";

      mimeType( contentType );

      int start = output.indexOf( "\r\n\r\n" );
      if ( start >= 0 ) start += 4;
      else {
        start = output.indexOf( "\n\n" );
        if ( start >= 0 ) start += 2;
      }

      if ( start >= 0 ) output = output.mid( start );

      stripHeader = false;
      data( output );
    } else {
      data( QByteArray::fromRawData( buffer, n ) );
    }
  }

  if ( forwardFile ) {
    fclose( fd );
  } else {
    pclose( fd );
  }

  finished();

  kDebug(7124) << "CgiProtocol::get - done";
}
Esempio n. 10
0
void tH3000LinkRx::RxSerialData(const QByteArray& rxData)
{
    bool messageReceived = false;

    // Receive buffer is a QByteArray
    // This could be optimised to be char array to reduce allocs and copies
    m_RxBuffer += rxData;

    int endIndex = m_RxBuffer.indexOf("\r\n");

    while(endIndex != -1)
    {
        QByteArray RxMessage = m_RxBuffer.left(endIndex);

        if(RxMessage.size() > 0)
        {
            bool messageOk = false;

#ifdef LOG_H3000_RX
            DbgPrintf("**** H3000 Rx %s", RxMessage.constData());
#endif
            // Check the checksum
            int checksumIndex = RxMessage.lastIndexOf('*');

            if(checksumIndex != -1)
            {
                unsigned char calcChecksum = static_cast<unsigned char>( tH3000Command::CalculateChecksum( RxMessage.left( checksumIndex) ) );
                unsigned char checksum = static_cast<unsigned char>( RxMessage.mid(checksumIndex + 1, 2).toInt(0, 16) );

                if(checksum == calcChecksum)
                {
                    messageOk = true;
                }
            }

            if(messageOk == true)
            {
                QByteArray strippedMessage = RxMessage.left(checksumIndex);

                if(RxMessage.at(0) == '#')
                {
                    emit H3000ReceivedEchoResponse(RxMessage);
                }
                else if(RxMessage.at(0) == 'V')
                {
                    ProcessReceivedValue(strippedMessage);
                }
                else if(RxMessage.at(0) == 'U') 
                {
                    ProcessReceivedTableData(strippedMessage);
                }
                else if(RxMessage.at(0) == 'L')
                {
                    ProcessReceivedPosition(strippedMessage);
                }
                else if(RxMessage.at(0) == 'T')
                {
                    ProcessReceivedUTC(strippedMessage);
                }
                else if(RxMessage.at(0) == 'M')
                {
                    ProcessReceivedTrueMagSetting(strippedMessage);
                }

                messageReceived = true;
            }
        }

        m_RxBuffer = m_RxBuffer.mid(endIndex + 2);

        endIndex = m_RxBuffer.indexOf("\r\n");
    }

    if((messageReceived) && (!m_DataReceived))
    {
        m_DataReceived = true;

        emit H3000LinkDataReceived();
    }
}
void wrapInFunction()
{

//! [0]
QByteArray ba("Hello");
//! [0]


//! [1]
QByteArray ba;
ba.resize(5);
ba[0] = 0x3c;
ba[1] = 0xb8;
ba[2] = 0x64;
ba[3] = 0x18;
ba[4] = 0xca;
//! [1]


//! [2]
for (int i = 0; i < ba.size(); ++i) {
    if (ba.at(i) >= 'a' && ba.at(i) <= 'f')
        cout << "Found character in range [a-f]" << endl;
}
//! [2]


//! [3]
QByteArray x("and");
x.prepend("rock ");         // x == "rock and"
x.append(" roll");          // x == "rock and roll"
x.replace(5, 3, "&");       // x == "rock & roll"
//! [3]


//! [4]
QByteArray ba("We must be <b>bold</b>, very <b>bold</b>");
int j = 0;
while ((j = ba.indexOf("<b>", j)) != -1) {
    cout << "Found <b> tag at index position " << j << endl;
    ++j;
}
//! [4]


//! [5]
QByteArray().isNull();          // returns true
QByteArray().isEmpty();         // returns true

QByteArray("").isNull();        // returns false
QByteArray("").isEmpty();       // returns true

QByteArray("abc").isNull();     // returns false
QByteArray("abc").isEmpty();    // returns false
//! [5]


//! [6]
QByteArray ba("Hello");
int n = ba.size();          // n == 5
ba.data()[0];               // returns 'H'
ba.data()[4];               // returns 'o'
ba.data()[5];               // returns '\0'
//! [6]


//! [7]
QByteArray().isEmpty();         // returns true
QByteArray("").isEmpty();       // returns true
QByteArray("abc").isEmpty();    // returns false
//! [7]


//! [8]
QByteArray ba("Hello world");
char *data = ba.data();
while (*data) {
    cout << "[" << *data << "]" << endl;
    ++data;
}
//! [8]


//! [9]
QByteArray ba;
for (int i = 0; i < 10; ++i)
    ba[i] = 'A' + i;
// ba == "ABCDEFGHIJ"
//! [9]


//! [10]
QByteArray ba("Stockholm");
ba.truncate(5);             // ba == "Stock"
//! [10]


//! [11]
QByteArray ba("STARTTLS\r\n");
ba.chop(2);                 // ba == "STARTTLS"
//! [11]


//! [12]
QByteArray x("free");
QByteArray y("dom");
x += y;
// x == "freedom"
//! [12]


//! [13]
QByteArray().isNull();          // returns true
QByteArray("").isNull();        // returns false
QByteArray("abc").isNull();     // returns false
//! [13]


//! [14]
QByteArray ba("Istambul");
ba.fill('o');
// ba == "oooooooo"

ba.fill('X', 2);
// ba == "XX"
//! [14]


//! [15]
QByteArray x("ship");
QByteArray y("air");
x.prepend(y);
// x == "airship"
//! [15]


//! [16]
QByteArray x("free");
QByteArray y("dom");
x.append(y);
// x == "freedom"
//! [16]


//! [17]
QByteArray ba("Meal");
ba.insert(1, QByteArray("ontr"));
// ba == "Montreal"
//! [17]


//! [18]
QByteArray ba("Montreal");
ba.remove(1, 4);
// ba == "Meal"
//! [18]


//! [19]
QByteArray x("Say yes!");
QByteArray y("no");
x.replace(4, 3, y);
// x == "Say no!"
//! [19]


//! [20]
QByteArray ba("colour behaviour flavour neighbour");
ba.replace(QByteArray("ou"), QByteArray("o"));
// ba == "color behavior flavor neighbor"
//! [20]


//! [21]
QByteArray x("sticky question");
QByteArray y("sti");
x.indexOf(y);               // returns 0
x.indexOf(y, 1);            // returns 10
x.indexOf(y, 10);           // returns 10
x.indexOf(y, 11);           // returns -1
//! [21]


//! [22]
QByteArray ba("ABCBA");
ba.indexOf("B");            // returns 1
ba.indexOf("B", 1);         // returns 1
ba.indexOf("B", 2);         // returns 3
ba.indexOf("X");            // returns -1
//! [22]


//! [23]
QByteArray x("crazy azimuths");
QByteArray y("az");
x.lastIndexOf(y);           // returns 6
x.lastIndexOf(y, 6);        // returns 6
x.lastIndexOf(y, 5);        // returns 2
x.lastIndexOf(y, 1);        // returns -1
//! [23]


//! [24]
QByteArray ba("ABCBA");
ba.lastIndexOf("B");        // returns 3
ba.lastIndexOf("B", 3);     // returns 3
ba.lastIndexOf("B", 2);     // returns 1
ba.lastIndexOf("X");        // returns -1
//! [24]


//! [25]
QByteArray url("ftp://ftp.qt-project.org/");
if (url.startsWith("ftp:"))
    ...
//! [25]


//! [26]
QByteArray url("http://qt-project.org/doc/qt-5.0/qtdoc/index.html");
if (url.endsWith(".html"))
    ...
//! [26]


//! [27]
QByteArray x("Pineapple");
QByteArray y = x.left(4);
// y == "Pine"
//! [27]


//! [28]
QByteArray x("Pineapple");
QByteArray y = x.right(5);
// y == "apple"
//! [28]


//! [29]
QByteArray x("Five pineapples");
QByteArray y = x.mid(5, 4);     // y == "pine"
QByteArray z = x.mid(5);        // z == "pineapples"
//! [29]


//! [30]
QByteArray x("Qt by DIGIA");
QByteArray y = x.toLower();
// y == "qt by digia"
//! [30]


//! [31]
QByteArray x("Qt by DIGIA");
QByteArray y = x.toUpper();
// y == "QT BY DIGIA"
//! [31]


//! [32]
QByteArray ba("  lots\t of\nwhitespace\r\n ");
ba = ba.simplified();
// ba == "lots of whitespace";
//! [32]


//! [33]
QByteArray ba("  lots\t of\nwhitespace\r\n ");
ba = ba.trimmed();
// ba == "lots\t of\nwhitespace";
//! [33]


//! [34]
QByteArray x("apple");
QByteArray y = x.leftJustified(8, '.');   // y == "apple..."
//! [34]


//! [35]
QByteArray x("apple");
QByteArray y = x.rightJustified(8, '.');    // y == "...apple"
//! [35]


//! [36]
QByteArray str("FF");
bool ok;
int hex = str.toInt(&ok, 16);     // hex == 255, ok == true
int dec = str.toInt(&ok, 10);     // dec == 0, ok == false
//! [36]


//! [37]
QByteArray str("FF");
bool ok;
long hex = str.toLong(&ok, 16);   // hex == 255, ok == true
long dec = str.toLong(&ok, 10);   // dec == 0, ok == false
//! [37]


//! [38]
QByteArray string("1234.56");
double a = string.toDouble();   // a == 1234.56
//! [38]


//! [39]
QByteArray text("Qt is great!");
text.toBase64();        // returns "UXQgaXMgZ3JlYXQh"
//! [39]

//! [39bis]
QByteArray text("<p>Hello?</p>");
text.toBase64(QByteArray::Base64 | QByteArray::OmitTrailingEquals);      // returns "PHA+SGVsbG8/PC9wPg"
text.toBase64(QByteArray::Base64);                                       // returns "PHA+SGVsbG8/PC9wPg=="
text.toBase64(QByteArray::Base64Url);                                    // returns "PHA-SGVsbG8_PC9wPg=="
text.toBase64(QByteArray::Base64Url | QByteArray::OmitTrailingEquals);   // returns "PHA-SGVsbG8_PC9wPg"
//! [39bis]


//! [40]
QByteArray ba;
int n = 63;
ba.setNum(n);           // ba == "63"
ba.setNum(n, 16);       // ba == "3f"
//! [40]


//! [41]
int n = 63;
QByteArray::number(n);              // returns "63"
QByteArray::number(n, 16);          // returns "3f"
QByteArray::number(n, 16).toUpper();  // returns "3F"
//! [41]


//! [42]
QByteArray ba = QByteArray::number(12.3456, 'E', 3);
// ba == 1.235E+01
//! [42]


//! [43]
 static const char mydata[] = {
    0x00, 0x00, 0x03, 0x84, 0x78, 0x9c, 0x3b, 0x76,
    0xec, 0x18, 0xc3, 0x31, 0x0a, 0xf1, 0xcc, 0x99,
    ...
    0x6d, 0x5b
};

QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata));
QDataStream in(&data, QIODevice::ReadOnly);
...
//! [43]


//! [44]
QByteArray text = QByteArray::fromBase64("UXQgaXMgZ3JlYXQh");
text.data();            // returns "Qt is great!"
//! [44]

//! [44bis]
QByteArray::fromBase64("PHA+SGVsbG8/PC9wPg==", QByteArray::Base64Encoding); // returns "<p>Hello?</p>"
QByteArray::fromBase64("PHA-SGVsbG8_PC9wPg==", QByteArray::Base64UrlEncoding); // returns "<p>Hello?</p>"
//! [44bis]


//! [45]
QByteArray text = QByteArray::fromHex("517420697320677265617421");
text.data();            // returns "Qt is great!"
//! [45]

//! [46]
QString tmp = "test";
QByteArray text = tmp.toLocal8Bit();
char *data = new char[text.size()];
strcpy(data, text.data());
delete [] data;
//! [46]

//! [47]
QString tmp = "test";
QByteArray text = tmp.toLocal8Bit();
char *data = new char[text.size() + 1];
strcpy(data, text.data());
delete [] data;
//! [47]

//! [48]
QByteArray ba1("ca\0r\0t");
ba1.size();                     // Returns 2.
ba1.constData();                // Returns "ca" with terminating \0.

QByteArray ba2("ca\0r\0t", 3);
ba2.size();                     // Returns 3.
ba2.constData();                // Returns "ca\0" with terminating \0.

QByteArray ba3("ca\0r\0t", 4);
ba3.size();                     // Returns 4.
ba3.constData();                // Returns "ca\0r" with terminating \0.

const char cart[] = {'c', 'a', '\0', 'r', '\0', 't'};
QByteArray ba4(QByteArray::fromRawData(cart, 6));
ba4.size();                     // Returns 6.
ba4.constData();                // Returns "ca\0r\0t" without terminating \0.
//! [48]

}
Esempio n. 12
0
int master(int argc, char **argv)
{
    //master
    LxQt::Application app(argc, argv, true);
    app.setQuitOnLastWindowClosed(false);

    if (1 >= argc)
    {
        usage(QObject::tr("%1: no command to run provided!").arg(app_master));
        return 1;
    } else
    {
        //simple help check
        std::string arg1(argv[1]);
        if ("-h" == arg1 || "--help" == arg1)
        {
            usage();
            return 0;
        } else if ("-v" == arg1 || "--version" == arg1)
        {
            version();
            return 0;
        }
        //any other arguments we simply forward to sudo
    }

    QStringList args = app.arguments();
    //check for provided command is done before
    args.removeAt(0);
    PasswordDialog dlg(args);
    dlg.setModal(true);
    app.setActiveWindow(&dlg);

    QScopedPointer<QProcess> sudo{new QProcess};
    QObject::connect(&dlg, &QDialog::finished, [&sudo, &dlg] (int result)
        {
            if (QDialog::Accepted == result)
            {
                sudo->write(QByteArray{}.append(dlg.password().append('\n')));
            } else
            {
                sudo->terminate();
                if (!sudo->waitForFinished(1000))
                    sudo->kill();
            }
        });

    //start background process -> sudo
    sudo->setProcessChannelMode(QProcess::ForwardedOutputChannel);
    sudo->setReadChannel(QProcess::StandardError);

    QString last_line;
    int ret;
    QObject::connect(sudo.data(), static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished)
            , [&app, &ret, &last_line, &dlg] (int exitCode, QProcess::ExitStatus exitStatus)
        {
            ret = QProcess::NormalExit == exitStatus ? exitCode : 255;
            if (0 != ret && last_line.startsWith(QStringLiteral("%1:").arg(sudo_prog)))
                QMessageBox(QMessageBox::Critical, dlg.windowTitle()
                        , QObject::tr("Child '%1' process failed!\n%2").arg(sudo_prog).arg(last_line), QMessageBox::Ok).exec();
            app.quit();
        });

    QObject::connect(sudo.data(), &QProcess::readyReadStandardError, [&sudo, &dlg, &last_line]
        {
            QByteArray err = sudo->readAllStandardError();
            if (sudo_pwd_prompt == err.constData())
            {
                dlg.show();
                return;
            }

            QTextStream{stderr, QIODevice::WriteOnly} << err;
            int nl_pos = err.lastIndexOf('\n');
            if (-1 == nl_pos)
                last_line += err;
            else
            {
                if (err.endsWith('\n'))
                    err.remove(err.size() - 1, 1);
                nl_pos = err.lastIndexOf('\n');
                if (-1 != nl_pos)
                    err.remove(0, nl_pos + 1);
                last_line = err;
            }
        });

    //forward all stdin to child
    QTextStream std_in{stdin, QIODevice::ReadOnly};
    QSocketNotifier stdin_watcher{0/*stdin*/, QSocketNotifier::Read};
    QObject::connect(&stdin_watcher, &QSocketNotifier::activated, [&std_in, &sudo]
        {
            QString line{std_in.readLine()};
            if (!std_in.atEnd())
                line += QLatin1Char('\n');
            sudo->write(line.toStdString().c_str());
            if (std_in.atEnd())
                sudo->closeWriteChannel();
        });

    sudo->start(sudo_prog, QStringList() << QStringLiteral("-S")
            << QStringLiteral("-p") << sudo_pwd_prompt
            << args);
    app.exec();

    sudo->waitForFinished(-1);
    return ret;
}
Esempio n. 13
0
void DownloadItem::metaDataChanged()
{
    // https://tools.ietf.org/html/rfc6266
    if (m_reply->hasRawHeader(QByteArray("Content-Disposition"))) {
        QByteArray header = m_reply->rawHeader(QByteArray("Content-Disposition"));
        int index = header.indexOf("filename=");
        if (index >= 0) {
            header = header.mid(index+9);
            if (header.startsWith("\"") || header.startsWith("'"))
                header = header.mid(1);
            if ((index = header.lastIndexOf("\"")) > 0)
                header = header.left(index);
            else if ((index = header.lastIndexOf("'")) > 0)
                header = header.left(index);
            m_fileName = QUrl::fromPercentEncoding(header);
        }
        // Sometimes "filename=" and "filename*=UTF-8''" is set.
        // So, search for this too.
        index = header.indexOf("filename*=UTF-8''");
        if (index >= 0) {
            header = header.mid(index+17);
            if (header.startsWith("\"") || header.startsWith("'"))
                header = header.mid(1);
            if ((index = header.lastIndexOf("\"")) > 0)
                header = header.left(index);
            else if ((index = header.lastIndexOf("'")) > 0)
                header = header.left(index);
            m_fileName = QUrl::fromPercentEncoding(header);
        }
    }

    QUrl url = m_reply->url();

    // If this is a redirected url use this instead
    QUrl redirectUrl = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
    if (!redirectUrl.isEmpty()) {
        QString s = redirectUrl.toString();
        std::cout << "Redirected to " << s.toStdString() << std::endl;

        QVariant header = m_reply->header(QNetworkRequest::LocationHeader);
        QString loc = header.toString();
        Q_UNUSED(loc);

        if (url != redirectUrl) {
            url = redirectUrl;

            if (m_reply) {
                disconnect(m_reply, SIGNAL(readyRead()), this, SLOT(downloadReadyRead()));
                disconnect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)),
                           this, SLOT(error(QNetworkReply::NetworkError)));
                disconnect(m_reply, SIGNAL(downloadProgress(qint64, qint64)),
                           this, SLOT(downloadProgress(qint64, qint64)));
                disconnect(m_reply, SIGNAL(metaDataChanged()),
                           this, SLOT(metaDataChanged()));
                disconnect(m_reply, SIGNAL(finished()),
                           this, SLOT(finished()));
                m_reply->close();
                m_reply->deleteLater();
            }

            m_reply = DownloadManager::getInstance()->networkAccessManager()->get(QNetworkRequest(url));
            init();
        }
    }
}
// Connect up a particular slot name, with optional arguments.
static void connect(QObject *qobj, PyObject *slot_obj,
        const QByteArray &slot_nm, const QByteArray &args)
{
    // Ignore if it's not an autoconnect slot.
    if (!slot_nm.startsWith("on_"))
        return;

    // Extract the names of the emitting object and the signal.
    int i;

    i = slot_nm.lastIndexOf('_');

    if (i - 3 < 1 || i + 1 >= slot_nm.size())
        return;

    QByteArray ename = slot_nm.mid(3, i - 3);
    QByteArray sname = slot_nm.mid(i + 1);

    // Find the emitting object and get its meta-object.
#if defined(QT_NO_MEMBER_TEMPLATES)
    QObject *eobj = qFindChild<QObject *>(qobj, ename);
#else
    QObject *eobj = qobj->findChild<QObject *>(ename);
#endif

    if (!eobj)
        return;

    const QMetaObject *mo = eobj->metaObject();

    // Got through the methods looking for a matching signal.
    PyObject *epyobj = 0;

    for (int m = 0; m < mo->methodCount(); ++m)
    {
        QMetaMethod mm = mo->method(m);

        if (mm.methodType() != QMetaMethod::Signal)
            continue;

#if QT_VERSION >= 0x050000
        QByteArray sig(mm.methodSignature());
#else
        QByteArray sig(mm.signature());
#endif

        if (Chimera::Signature::name(sig) != sname)
            continue;

        // If we have slot arguments then they must match as well.
        if (!args.isEmpty() && Chimera::Signature::arguments(sig) != args)
            continue;

        // Add the type character.
        sig.prepend('2');

        // Get the wrapper now we know it is needed.
        if (!epyobj)
        {
            epyobj = sipConvertFromType(eobj, sipType_QObject, 0);

            if (!epyobj)
                break;
        }

        // Connect the signal.
        PyObject *res = sipConnectRx(epyobj, sig.constData(), slot_obj, 0, 0);
        Py_XDECREF(res);
    }

    Py_XDECREF(epyobj);
}
Esempio n. 15
0
char *MANProtocol::readManPage(const char *_filename)
{
    QByteArray filename = _filename;
    QByteArray array;

    /* Determine type of man page file by checking its path. Determination by
     * MIME type with KMimeType doesn't work reliablely. E.g., Solaris 7:
     * /usr/man/sman7fs/pcfs.7fs -> text/x-csrc : WRONG
     * If the path name constains the string sman, assume that it's SGML and
     * convert it to roff format (used on Solaris). */
    //QString file_mimetype = KMimeType::findByPath(QString(filename), 0, false)->name();
    if (QString(filename).contains("sman", Qt::CaseInsensitive)) //file_mimetype == "text/html" || )
    {
        KProcess proc;
        // Determine path to sgml2roff, if not already done.
        getProgramPath();
        proc << mySgml2RoffPath << filename;
        proc.setOutputChannelMode( KProcess::OnlyStdoutChannel );
        proc.execute();
        array = proc.readAllStandardOutput();
    }
    else
    {
      if (QDir::isRelativePath(filename))
      {
          qCDebug(KIO_MAN_LOG) << "relative " << filename;
          filename = QDir::cleanPath(lastdir + '/' + filename).toUtf8();
          qCDebug(KIO_MAN_LOG) << "resolved to " << filename;
      }

      lastdir = filename.left(filename.lastIndexOf('/'));

      if ( !QFile::exists(QFile::decodeName(filename)) )  // if given file does not exist, find with suffix
      {
          qCDebug(KIO_MAN_LOG) << "not existing " << filename;
          QDir mandir(lastdir);
          mandir.setNameFilters(QStringList() << (filename.mid(filename.lastIndexOf('/') + 1) + ".*"));
          filename = lastdir + '/' + QFile::encodeName(mandir.entryList().first());
          qCDebug(KIO_MAN_LOG) << "resolved to " << filename;
      }

      QIODevice *fd = KFilterDev::deviceForFile(filename);

      if ( !fd || !fd->open(QIODevice::ReadOnly))
      {
         delete fd;
         return 0;
      }
      array = fd->readAll();
      qCDebug(KIO_MAN_LOG) << "read " << array.size();
      fd->close();
      delete fd;
    }

    if (array.isEmpty())
      return 0;

    // as we do not know in which encoding the man source is, try to automatically
    // detect it and always return it as UTF-8
    KEncodingProber encodingProber;
    encodingProber.feed(array);
    qCDebug(KIO_MAN_LOG) << "auto-detect encoding for" << filename << "guess=" << encodingProber.encoding()
                 << "confidence=" << encodingProber.confidence();
    QString out = QTextCodec::codecForName(encodingProber.encoding())->toUnicode(array);
    array = out.toUtf8();

    const int len = array.size();
    char *buf = new char[len + 4];
    memmove(buf + 1, array.data(), len);
    buf[0] = buf[len+1] = '\n'; // Start and end with an end of line
    buf[len+2] = buf[len+3] = '\0'; // Two NUL characters at end

    return buf;
}
Esempio n. 16
0
//-------------------------------------------------------------------------------------------------
void ExchangeRate::slotReplyFin(QNetworkReply *netrep)
{
    if (netrep->error())
    {
        QMessageBox::warning(this, 0, tr("Connection error:") + ' ' + netrep->errorString());
        return;
    }

    const QByteArray baRead = netrep->readAll();
    int iSep = baRead.indexOf("<a href=\"/control/en/curmetal/detail/currency?period=daily\">", 40000);
    if (iSep > 0)
    {
        iSep = baRead.lastIndexOf("</td>", iSep);
        if (iSep > 0)
        {
            const QString strDate = baRead.mid(iSep-10, 10);        //[10 = "dd.MM.yyyy"]
            if (QDateTime::fromString(strDate, "dd.MM.yyyy").isValid())
            {
                iSep = baRead.indexOf("<td class=\"attribute\">100&nbsp;US Dollar</td>", iSep+70);
                if (iSep > 0)
                {
                    iSep = baRead.indexOf("<td class=\"value\" nowrap=\"nowrap\">", iSep+45);
                    if (iSep > 0)
                    {
                        iSep += 34;
                        int iEnd = baRead.indexOf('\n', iSep);
                        if (iEnd > 0)
                        {
                            const double dPerUsd = baRead.mid(iSep, iEnd-iSep-1).toDouble();
                            if (dPerUsd > 300.0 && dPerUsd < 8000.0)
                            {
                                iSep = baRead.indexOf("<td class=\"attribute\">100&nbsp;EURO</td>", iSep+100);
                                if (iSep > 0)
                                {
                                    iSep = baRead.indexOf("<td class=\"value\" nowrap=\"nowrap\">", iSep+40);
                                    if (iSep > 0)
                                    {
                                        iSep += 34;
                                        iEnd = baRead.indexOf('\n', iSep);
                                        if (iEnd > 0)
                                        {
                                            const double dPerEur = baRead.mid(iSep, iEnd-iSep-1).toDouble();
                                            if (dPerEur > 300.0 && dPerEur < 8000.0)
                                            {
                                                iSep = baRead.indexOf("<td class=\"attribute\">10&nbsp;Russian ruble</td>", iSep+100);
                                                if (iSep > 0)
                                                {
                                                    iSep = baRead.indexOf("<td class=\"value\" nowrap=\"nowrap\">", iSep+48);
                                                    if (iSep > 0)
                                                    {
                                                        iSep += 34;
                                                        iEnd = baRead.indexOf('\n', iSep);
                                                        if (iEnd > 0)
                                                        {
                                                            const double dPerRub = baRead.mid(iSep, iEnd-iSep-1).toDouble();
                                                            if (dPerRub > 1.0 && dPerRub < 10.0)
                                                            {
                                                                iSep = 0;
                                                                dUahPerUsd = dPerUsd/100.0;
                                                                dUahPerEur = dPerEur/100.0;
                                                                dUahPerRub = dPerRub/10.0;

                                                                const QString strUahPerUsd = QString::number(dUahPerUsd, 'f', 6),
                                                                        strUahPerEur = QString::number(dUahPerEur, 'f', 6),
                                                                        strUahPerRub = QString::number(dUahPerRub, 'f', 5);

                                                                lblNote->setText(strDate + "\n1 USD = " + strUahPerUsd + " UAH\n1 EUR = " + strUahPerEur + " UAH\n1 UAH = " + QString::number(1.0/dUahPerRub, 'f', 6) + " RUB");

                                                                QSettings stg(strAppStg, QSettings::IniFormat);
                                                                stg.beginGroup("Settings");
                                                                stg.setValue("DateTime", strDate);
                                                                stg.setValue("USD", strUahPerUsd);
                                                                stg.setValue("EUR", strUahPerEur);
                                                                stg.setValue("RUB", strUahPerRub);
                                                                stg.endGroup();

                                                                lblInfo->setText(tr("Successfully"));
                                                                gbMain->setEnabled(true);
                                                                QTimer::singleShot(1300, lblInfo, SLOT(clear()));
                                                            }
                                                            else
                                                                iSep = 114;
                                                        }
                                                        else
                                                            iSep = 113;
                                                    }
                                                    else
                                                        iSep = 112;
                                                }
                                                else
                                                    iSep = 111;
                                            }
                                            else
                                                iSep = 110;
                                        }
                                        else
                                            iSep = 109;
                                    }
                                    else
                                        iSep = 108;
                                }
                                else
                                    iSep = 107;
                            }
                            else
                                iSep = 106;
                        }
                        else
                            iSep = 105;
                    }
                    else
                        iSep = 104;
                }
                else
                    iSep = 103;
            }
            else
                iSep = 102;
        }
        else
            iSep = 101;
    }
    else
        iSep = 100;

    if (iSep)
        QMessageBox::warning(this, 0, tr("Error:") + " #" + QString::number(iSep));
}
Esempio n. 17
0
static void mirallLogCatcher(QtMsgType, const QMessageLogContext &ctx, const QString &message) {
    QByteArray file = ctx.file;
    file = file.mid(file.lastIndexOf('/') + 1);
    Logger::instance()->mirallLog( QString::fromLocal8Bit(file) + QLatin1Char(':') + QString::number(ctx.line)
                                    + QLatin1Char(' ')  + message) ;
}
Esempio n. 18
0
int master(int argc, char **argv)
{
    //master
    LxQt::Application app(argc, argv);
    app.setQuitOnLastWindowClosed(false);

    if (1 >= argc)
    {
        usage(QObject::tr("%1: no command to run provided!").arg(app_master));
        return 1;
    } else
    {
        //simple help check
        std::string arg1(argv[1]);
        if ("-h" == arg1 || "--help" == arg1)
        {
            usage();
            return 0;
        } else if ("-v" == arg1 || "--version" == arg1)
        {
            version();
            return 0;
        }
        //any other arguments we simply forward to sudo
    }

    QString pid = QStringLiteral("%1").arg(app.applicationPid());
    Communication comm(QStringLiteral("%1/%2").arg(app_master).arg(pid), true/*master*/);
    if (!comm.valid())
        return 1;

    //set environment for child
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    env.insert(ENV_PID, pid);
    QFileInfo fi(argv[0]);
    if (nullptr != strchr(argv[0], '/'))
        fi.setFile(fi.dir(), app_slave);
    else
        fi.setFile(QDir(install_dir), app_slave);
    env.insert(ENV_SUDO_ASKPASS, fi.filePath());

    QStringList args = app.arguments();
    //check for provided command is done before
    args.removeAt(0);
    PasswordDialog dlg(args);
    dlg.setModal(true);
    dlg.setWindowIcon(QIcon::fromTheme("security-high"));
    app.setActiveWindow(&dlg);

    QScopedPointer<QProcess> sudo{new QProcess};
    QObject::connect(&comm, &Communication::passwordNeeded, [&dlg, &comm, &sudo]
        {
            dlg.show();
        });
    QObject::connect(&dlg, &QDialog::finished, [&comm, &sudo, &dlg] (int result)
        {
            if (QDialog::Accepted == result)
            {
                comm.setPassword(dlg.password());
                comm.waitForReady();
            } else
            {
                sudo->terminate();
                if (!sudo->waitForFinished(1000))
                    sudo->kill();
            }
        });
    comm.waitForReady();

    //start background process -> sudo
    sudo->setProcessEnvironment(env);
    sudo->setInputChannelMode(QProcess::ForwardedInputChannel);
    sudo->setProcessChannelMode(QProcess::ForwardedOutputChannel);
    sudo->setReadChannel(QProcess::StandardError);

    QString last_line;
    int ret;
    QObject::connect(sudo.data(), static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished)
            , [&app, &ret, &last_line, &dlg] (int exitCode, QProcess::ExitStatus exitStatus)
        {
            ret = QProcess::NormalExit == exitStatus ? exitCode : 255;
            if (0 != ret && last_line.startsWith(QStringLiteral("%1:").arg(LXQTSUDO_SUDO)))
                QMessageBox(QMessageBox::Critical, dlg.windowTitle()
                        , QObject::tr("Child '%1' process failed!\n%2").arg(LXQTSUDO_SUDO).arg(last_line), QMessageBox::Ok).exec();
            app.quit();
        });

    QObject::connect(sudo.data(), &QProcess::readyReadStandardError, [&sudo, &last_line]
        {
            QByteArray err = sudo->readAllStandardError();
            std::cerr << err.constData();
            std::cerr.flush();
            int nl_pos = err.lastIndexOf('\n');
            if (-1 == nl_pos)
                last_line += err;
            else
            {
                if (err.endsWith('\n'))
                    err.remove(err.size() - 1, 1);
                nl_pos = err.lastIndexOf('\n');
                if (-1 != nl_pos)
                    err.remove(0, nl_pos + 1);
                last_line = err;
            }
        });

    sudo->start(QStringLiteral(LXQTSUDO_SUDO), QStringList() << QStringLiteral("-A")
            << args);
    app.exec();

    sudo->waitForFinished(-1);
    return ret;
}
Esempio n. 19
0
void SearchEnginesManager::addEngineFromForm(const QWebElement &element, WebView* view)
{
    QWebElement formElement = element.parent();

    while (!formElement.isNull()) {
        if (formElement.tagName().toLower() == QLatin1String("form")) {
            break;
        }

        formElement = formElement.parent();
    }

    if (formElement.isNull()) {
        return;
    }

    const QString method = formElement.hasAttribute("method") ? formElement.attribute("method").toUpper() : "GET";
    bool isPost = method == QLatin1String("POST");

    QUrl actionUrl = QUrl::fromEncoded(formElement.attribute("action").toUtf8());

    if (actionUrl.isRelative()) {
        actionUrl = view->url().resolved(actionUrl);
    }

    QUrl parameterUrl = actionUrl;

    if (isPost) {
        parameterUrl = QUrl("http://foo.bar");
    }

#if QT_VERSION >= 0x050000
    QUrlQuery query(parameterUrl);
    query.addQueryItem(element.attribute("name"), "%s");

    QWebElementCollection allInputs = formElement.findAll("input");
    foreach (QWebElement e, allInputs) {
        if (element == e || !e.hasAttribute("name")) {
            continue;
        }

        query.addQueryItem(e.attribute("name"), e.evaluateJavaScript("this.value").toString());
    }

    parameterUrl.setQuery(query);
#else
    QList<QPair<QByteArray, QByteArray> > queryItems;

    QPair<QByteArray, QByteArray> item;
    item.first = element.attribute("name").toUtf8();
    item.second = "%s";
    queryItems.append(item);

    QWebElementCollection allInputs = formElement.findAll("input");
    foreach (QWebElement e, allInputs) {
        if (element == e || !e.hasAttribute("name")) {
            continue;
        }

        QPair<QByteArray, QByteArray> item;
        item.first = QUrl::toPercentEncoding(e.attribute("name").toUtf8());
        item.second = QUrl::toPercentEncoding(e.evaluateJavaScript("this.value").toByteArray());

        queryItems.append(item);
    }
    parameterUrl.setEncodedQueryItems(parameterUrl.encodedQueryItems() + queryItems);
#endif

    if (!isPost) {
        actionUrl = parameterUrl;
    }

    SearchEngine engine;
    engine.name = view->title();
    engine.icon = view->icon();
    engine.url = actionUrl.toEncoded();

    if (isPost) {
        QByteArray data = parameterUrl.toEncoded(QUrl::RemoveScheme);
        engine.postData = data.contains('?') ? data.mid(data.lastIndexOf('?') + 1) : QByteArray();
    }

    EditSearchEngine dialog(SearchEnginesDialog::tr("Add Search Engine"), view);
    dialog.setName(engine.name);
    dialog.setIcon(engine.icon);
    dialog.setUrl(engine.url);
    dialog.setPostData(engine.postData);

    if (dialog.exec() != QDialog::Accepted) {
        return;
    }

    engine.name = dialog.name();
    engine.icon = dialog.icon();
    engine.url = dialog.url();
    engine.shortcut = dialog.shortcut();
    engine.postData = dialog.postData().toUtf8();

    if (engine.name.isEmpty() || engine.url.isEmpty()) {
        return;
    }

    addEngine(engine);
}
Esempio n. 20
0
int runMoc(int _argc, char **_argv)
{
    bool autoInclude = true;
    Preprocessor pp;
    Moc moc;
    pp.macros["Q_MOC_RUN"];
    pp.macros["__cplusplus"];
    QByteArray filename;
    QByteArray output;
    FILE *in = 0;
    FILE *out = 0;
    bool ignoreConflictingOptions = false;

    QVector<QByteArray> argv;
    argv.resize(_argc - 1);
    for (int n = 1; n < _argc; ++n)
        argv[n - 1] = _argv[n];
    int argc = argv.count();

    for (int n = 0; n < argv.count(); ++n) {
        if (argv.at(n).startsWith('@')) {
            QByteArray optionsFile = argv.at(n);
            optionsFile.remove(0, 1);
            if (optionsFile.isEmpty())
                error("The @ option requires an input file");
            QFile f(QString::fromLatin1(optionsFile.constData()));
            if (!f.open(QIODevice::ReadOnly | QIODevice::Text))
                error("Cannot open options file specified with @");
            argv.remove(n);
            while (!f.atEnd()) {
                QByteArray line = f.readLine().trimmed();
                if (!line.isEmpty())
                    argv.insert(n++, line);
            }
        }
    }

    argc = argv.count();

    for (int n = 0; n < argc; ++n) {
        QByteArray arg(argv[n]);
        if (arg[0] != '-') {
            if (filename.isEmpty()) {
                filename = arg;
                continue;
            }
            error("Too many input files specified");
        }
        QByteArray opt = arg.mid(1);
        bool more = (opt.size() > 1);
        switch (opt[0]) {
        case 'o': // output redirection
            if (!more) {
                if (!(n < argc-1))
                    error("Missing output file name");
                output = argv[++n];
            } else
                output = opt.mid(1);
            break;
        case 'E': // only preprocessor
            pp.preprocessOnly = true;
            break;
        case 'i': // no #include statement
            if (more)
                error();
            moc.noInclude        = true;
            autoInclude = false;
            break;
        case 'f': // produce #include statement
            if (ignoreConflictingOptions)
                break;
            moc.noInclude        = false;
            autoInclude = false;
            if (opt[1])                        // -fsomething.h
                moc.includeFiles.append(opt.mid(1));
            break;
        case 'p': // include file path
            if (ignoreConflictingOptions)
                break;
            if (!more) {
                if (!(n < argc-1))
                    error("Missing path name for the -p option.");
                moc.includePath = argv[++n];
            } else {
                moc.includePath = opt.mid(1);
            }
            break;
        case 'I': // produce #include statement
            if (!more) {
                if (!(n < argc-1))
                    error("Missing path name for the -I option.");
                pp.includes += Preprocessor::IncludePath(argv[++n]);
            } else {
                pp.includes += Preprocessor::IncludePath(opt.mid(1));
            }
            break;
        case 'F': // minimalistic framework support for the mac
            if (!more) {
                if (!(n < argc-1))
                    error("Missing path name for the -F option.");
                Preprocessor::IncludePath p(argv[++n]);
                p.isFrameworkPath = true;
                pp.includes += p;
            } else {
                Preprocessor::IncludePath p(opt.mid(1));
                p.isFrameworkPath = true;
                pp.includes += p;
            }
            break;
        case 'D': // define macro
            {
                QByteArray name;
                QByteArray value("1");
                if (!more) {
                    if (n < argc-1)
                        name = argv[++n];
                } else
                    name = opt.mid(1);
                int eq = name.indexOf('=');
                if (eq >= 0) {
                    value = name.mid(eq + 1);
                    name = name.left(eq);
                }
                if (name.isEmpty())
                    error("Missing macro name");
                Macro macro;
                macro.symbols += Symbol(0, PP_IDENTIFIER, value);
                pp.macros.insert(name, macro);

            }
            break;
        case 'U':
            {
                QByteArray macro;
                if (!more) {
                    if (n < argc-1)
                        macro = argv[++n];
                } else
                    macro = opt.mid(1);
                if (macro.isEmpty())
                    error("Missing macro name");
                pp.macros.remove(macro);

            }
            break;
        case 'v':  // version number
            if (more && opt != "version")
                error();
            fprintf(stderr, "Qt Meta Object Compiler version %d (Qt %s)\n",
                    mocOutputRevision, QT_VERSION_STR);
            return 1;
        case 'n': // don't display warnings
            if (ignoreConflictingOptions)
                break;
            if (opt != "nw")
                error();
            moc.displayWarnings = false;
            break;
        case 'h': // help
            if (more && opt != "help")
                error();
            else
                error(0); // 0 means usage only
            break;
        case '-':
            if (more && arg == "--ignore-option-clashes") {
                // -- ignore all following moc specific options that conflict
                // with for example gcc, like -pthread conflicting with moc's
                // -p option.
                ignoreConflictingOptions = true;
                break;
            }
            // fall through
        default:
            error();
        }
    }


    if (autoInclude) {
        int ppos = filename.lastIndexOf('.');
        moc.noInclude = (ppos >= 0
                         && tolower(filename[ppos + 1]) != 'h'
                         && tolower(filename[ppos + 1]) != QDir::separator().toLatin1()
                        );
    }
    if (moc.includeFiles.isEmpty()) {
        if (moc.includePath.isEmpty()) {
            if (filename.size()) {
                if (output.size())
                    moc.includeFiles.append(combinePath(filename, output));
                else
                    moc.includeFiles.append(filename);
            }
        } else {
            moc.includeFiles.append(combinePath(filename, filename));
        }
    }

    if (filename.isEmpty()) {
        filename = "standard input";
        in = stdin;
    } else {
#if defined(_MSC_VER) && _MSC_VER >= 1400
		if (fopen_s(&in, filename.data(), "rb")) {
#else
        in = fopen(filename.data(), "rb");
		if (!in) {
#endif
            fprintf(stderr, "moc: %s: No such file\n", (const char*)filename);
            return 1;
        }
        moc.filename = filename;
    }

    moc.currentFilenames.push(filename);

    // 1. preprocess
    moc.symbols = pp.preprocessed(moc.filename, in);
    fclose(in);

    if (!pp.preprocessOnly) {
        // 2. parse
        moc.parse();
    }

    // 3. and output meta object code

    if (output.size()) { // output file specified
#if defined(_MSC_VER) && _MSC_VER >= 1400
        if (fopen_s(&out, output.data(), "w"))
#else
        out = fopen(output.data(), "w"); // create output file
        if (!out)
#endif
        {
            fprintf(stderr, "moc: Cannot create %s\n", (const char*)output);
            return 1;
        }
    } else { // use stdout
        out = stdout;
    }

    if (pp.preprocessOnly) {
        fprintf(out, "%s\n", composePreprocessorOutput(moc.symbols).constData());
    } else {
        if (moc.classList.isEmpty())
            moc.warning("No relevant classes found. No output generated.");
        else
            moc.generate(out);
    }

    if (output.size())
        fclose(out);

    return 0;
}

QT_END_NAMESPACE

int main(int _argc, char **_argv)
{
    return QT_PREPEND_NAMESPACE(runMoc)(_argc, _argv);
}
Esempio n. 21
0
static QFontEngine::FaceId fontFile(const QByteArray &_xname, QFreetypeFace **freetype, int *synth)
{
    *freetype = 0;
    *synth = 0;

    QByteArray xname = _xname.toLower();

    int pos = 0;
    int minus = 0;
    while (minus < 5 && (pos = xname.indexOf('-', pos + 1)))
        ++minus;
    QByteArray searchname = xname.left(pos);
    while (minus < 12 && (pos = xname.indexOf('-', pos + 1)))
        ++minus;
    QByteArray encoding = xname.mid(pos + 1);
    //qDebug("xname='%s', searchname='%s', encoding='%s'", xname.data(), searchname.data(), encoding.data());
    QStringList fontpath = fontPath();
    QFontEngine::FaceId face_id;
    face_id.index = 0;

    QByteArray best_mapping;

    for (QStringList::ConstIterator it = fontpath.constBegin(); it != fontpath.constEnd(); ++it) {
        if (!(*it).startsWith(QLatin1Char('/')))
            continue; // not a path name, a font server
        QString fontmapname;
        int num = 0;
        // search font.dir and font.scale for the right file
        while (num < 2) {
            if (num == 0)
                fontmapname = (*it) + QLatin1String("/fonts.scale");
            else
                fontmapname = (*it) + QLatin1String("/fonts.dir");
            ++num;
            //qWarning(fontmapname);
            QFile fontmap(fontmapname);
            if (!fontmap.open(QIODevice::ReadOnly))
                continue;
            while (!fontmap.atEnd()) {
                QByteArray mapping = fontmap.readLine();
                QByteArray lmapping = mapping.toLower();

                //qWarning(xfontname);
                //qWarning(mapping);
                if (!lmapping.contains(searchname))
                    continue;
                int index = mapping.indexOf(' ');
                QByteArray ffn = mapping.mid(0,index);
                // remove bitmap formats freetype can't handle
                if (ffn.contains(".spd") || ffn.contains(".phont"))
                    continue;
                bool best_match = false;
                if (!best_mapping.isEmpty()) {
                    if (lmapping.contains("-0-0-0-0-")) { // scalable font
                        best_match = true;
                        goto found;
                    }
                    if (lmapping.contains(encoding) && !best_mapping.toLower().contains(encoding))
                        goto found;
                    continue;
                }

            found:
                int colon = ffn.lastIndexOf(':');
                if (colon != -1) {
                    QByteArray s = ffn.left(colon);
                    ffn = ffn.mid(colon + 1);
                    if (s.contains("ds="))
                        *synth |= QFontEngine::SynthesizedBold;
                    if (s.contains("ai="))
                        *synth |= QFontEngine::SynthesizedItalic;
                }
                face_id.filename = (*it).toLocal8Bit() + '/' + ffn;
                best_mapping = mapping;
                if (best_match)
                    goto end;
            }
        }
    }
end:
//     qDebug("fontfile for %s is from '%s'\n    got %s synth=%d", xname.data(),
//            best_mapping.data(), face_id.filename.data(), *synth);
    *freetype = QFreetypeFace::getFace(face_id);
    if (!*freetype) {
        face_id.index = 0;
        face_id.filename = QByteArray();
    }
    return face_id;
}
Esempio n. 22
0
void YandexNarodUploadJob::progressReply()
{
	QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
	Q_ASSERT(reply);
	if (!processReply(reply))
		return;

	QByteArray data = reply->readAll();
#if HAS_NO_TOKEN_AUTHORIZATION
	int start = data.indexOf('{');
	int end = data.lastIndexOf('}');
	QVariantMap map = Json::parse(data.mid(start, end - start + 1)).toMap();
#else
	QVariant tmpVar;
	int dataBegin = data.indexOf('(') + 1;
	int dataEnd = data.lastIndexOf(')');
	int dataLength = dataEnd - dataBegin;
	if (dataBegin < 0 || dataEnd < 0 || dataLength < 0) {
		dataBegin = 0;
		dataLength = data.length();
	}
	Json::parseRecord(tmpVar, data.constData() + dataBegin, &dataLength);
	QVariantMap map = tmpVar.toMap();
#endif

	debug() << "progress" << reply->request().url() << data << map;
	debug() << "progress" << reply->rawHeader("Set-Cookie");
	int newProgress = fileSize() * (map.value("percent").toDouble() / 100.0);
	if (newProgress > progress())
		setFileProgress(newProgress);

	QString status = map.value("status").toString();
	if (status == "upload") {
		m_timer.start();
//		{
//		"tid": "1263553646SvsF9FFimF5thmoM2kGTwxL9",
//		"status": "upload",
//		"percent": "94.11",
//		"ipercent": 94,
//		"random": "1263553668S4gHxbB2nJSd2clhhfYimsfM",
//		"time": { "min": "0","sec": "01" }
//		}
	} else if (status == "done" && state() != Finished) {
//		{
//		"tid": "1263553646SvsF9FFimF5thmoM2kGTwxL9",
//		"status": "done",
//		"fids": "8433938",
//		"files": [{ "fid": "8433938", "hash": "16928325000", "name": "Makefile", "size": "146305" }],
//		"percent": "100.00",
//		"ipercent": 100,
//		"random": "1263553670cshMPkykOsHbaCnIQ5ehEOKd",
//		"time": { "min": "0","sec": "00" }
//		}

		setState(Finished);
		QVariantMap varMap = map.value("files").toList().value(0).toMap();
		if (!varMap.isEmpty() && chatUnit()) {
			debug() << "done" << chatUnit()->title() << varMap;

			QString url(QLatin1String("http://narod.ru/disk/"));
			url += varMap.value("hash").toString();
			url += QLatin1Char('/');
			url += varMap.value("name").toString();
			url += QLatin1String(".html");
			debug() << url;

			QString sendmsg = Config().group("yandex").group("narod")
							  .value("template", tr("File sent: %N (%S bytes)\n%U",
													"Don't remove format arguments"));
			sendmsg.replace("%N", varMap.value("name").toString());
			sendmsg.replace("%U", url);
			sendmsg.replace("%S", varMap.value("size").toString());

			//Append message to chatunit
			Message msg(sendmsg);
			msg.setIncoming(false);
			msg.setProperty("service", true);
			if (ChatSession *s = ChatLayer::get(chatUnit(), false))
				s->appendMessage(msg);
			msg.setProperty("service", false);
			chatUnit()->account()->getUnitForSession(chatUnit())->send(msg);
		}
	}
}