コード例 #1
0
ファイル: local_peer.cpp プロジェクト: 13W/icq-desktop
void LocalPeer::receiveConnection()
{
#ifdef _WIN32
    QLocalSocket* socket = server_->nextPendingConnection();
    if (!socket)
        return;

    while (socket->bytesAvailable() < (int)sizeof(quint32))
        socket->waitForReadyRead();

    QDataStream ds(socket);
    QByteArray uMsg;
    quint32 remaining;
    ds >> remaining;
    uMsg.resize(remaining);
    int got = 0;
    char* uMsgBuf = uMsg.data();
    do 
	{
        got = ds.readRawData(uMsgBuf, remaining);
        remaining -= got;
        uMsgBuf += got;
    } 
    while (remaining && got >= 0 && socket->waitForReadyRead(2000));

    if (got < 0) 
	{
        delete socket;
        return;
    }

    QString message(QString::fromUtf8(uMsg));
	if (message == crossprocess_message_get_process_id)
	{
		unsigned int process_id = 0;
		process_id = ::GetCurrentProcessId();
		socket->write((const char*) &process_id, sizeof(process_id));
	}
    else if (message == crossprocess_message_get_hwnd_activate)
    {
        unsigned int hwnd = 0;
        if (wnd_)
        {
            hwnd = (unsigned int) wnd_->winId();
            wnd_->activateFromEventLoop();
        }
        socket->write((const char*) &hwnd, sizeof(hwnd));
    }
	else
	{
		socket->write("icq", qstrlen("icq"));
	}
	    
    socket->waitForBytesWritten(1000);
    socket->waitForDisconnected(1000);
    delete socket;
	
	if (message == crossprocess_message_shutdown_process)
	{
		QApplication::exit(0);
    }
#endif //_WIN32
}
コード例 #2
0
ファイル: mysql.cpp プロジェクト: AirBayCreative/fibjs
result_t mysql::execute(const char *sql, obj_ptr<DBResult_base> &retVal, AsyncEvent *ac)
{
    return execute(sql, (int32_t) qstrlen(sql), retVal);
}
コード例 #3
0
/*
  This opens the specified library, mmaps it into memory, and searches
  for the QT_PLUGIN_VERIFICATION_DATA.  The advantage of this approach is that
  we can get the verification data without have to actually load the library.
  This lets us detect mismatches more safely.

  Returns false if version information is not present, or if the
                information could not be read.
  Returns  true if version information is present and successfully read.
*/
static bool qt_unix_query(const QString &library, QLibraryPrivate *lib)
{
    QFile file(library);
    if (!file.open(QIODevice::ReadOnly)) {
        if (lib)
            lib->errorString = file.errorString();
        if (qt_debug_component()) {
            qWarning("%s: %s", (const char*) QFile::encodeName(library),
                qPrintable(qt_error_string(errno)));
        }
        return false;
    }

    QByteArray data;
    const char *filedata = 0;
    ulong fdlen = file.size();
    filedata = (char *) file.map(0, fdlen);
    if (filedata == 0) {
        // try reading the data into memory instead
        data = file.readAll();
        filedata = data.constData();
        fdlen = data.size();
    }

    /*
       ELF binaries on GNU, have .qplugin sections.
    */
    bool hasMetaData = false;
    long pos = 0;
    const char pattern[] = "QTMETADATA  ";
    const ulong plen = qstrlen(pattern);
#if defined (Q_OF_ELF) && defined(Q_CC_GNU)
    int r = QElfParser().parse(filedata, fdlen, library, lib, &pos, &fdlen);
    if (r == QElfParser::Corrupt || r == QElfParser::NotElf) {
            if (lib && qt_debug_component()) {
                qWarning("QElfParser: %s",qPrintable(lib->errorString));
            }
            return false;
    } else if (r == QElfParser::QtMetaDataSection) {
        long rel = qt_find_pattern(filedata + pos, fdlen, pattern, plen);
        if (rel < 0)
            pos = -1;
        else
            pos += rel;
        hasMetaData = true;
    }
#else
    pos = qt_find_pattern(filedata, fdlen, pattern, plen);
    if (pos > 0)
        hasMetaData = true;
#endif // defined(Q_OF_ELF) && defined(Q_CC_GNU)

    bool ret = false;

    if (pos >= 0) {
        if (hasMetaData) {
            const char *data = filedata + pos;
            QJsonDocument doc = QLibraryPrivate::fromRawMetaData(data);
            lib->metaData = doc.object();
            if (qt_debug_component())
                qWarning("Found metadata in lib %s, metadata=\n%s\n",
                         library.toLocal8Bit().constData(), doc.toJson().constData());
            ret = !doc.isNull();
        }
    }

    if (!ret && lib)
        lib->errorString = QLibrary::tr("Plugin verification data mismatch in '%1'").arg(library);
    file.close();
    return ret;
}
コード例 #4
0
ファイル: numberh.cpp プロジェクト: aurelienRT1/ezpublish
static QString translationAttempt( const QString& oldTranslation,
				   const char *oldSource,
				   const char *newSource )
{
    int p = zeroKey( oldSource ).contains( '0' );
    int oldSourceLen = qstrlen( oldSource );
    QString attempt;
    QStringList oldNumbers;
    QStringList newNumbers;
    QMemArray<bool> met( p );
    QMemArray<int> matchedYet( p );
    int i, j;
    int k = 0, ell, best;
    int m, n;
    int pass;

    /*
      This algorithm is hard to follow, so we'll consider an example
      all along: oldTranslation is "XeT 3.0", oldSource is "TeX 3.0"
      and newSource is "XeT 3.1".

      First, we set up two tables: oldNumbers and newNumbers. In our
      example, oldNumber[0] is "3.0" and newNumber[0] is "3.1".
    */
    for ( i = 0, j = 0; i < oldSourceLen; i++, j++ ) {
	m = numberLength( oldSource + i );
	n = numberLength( newSource + j );
	if ( m > 0 ) {
	    oldNumbers.append( QCString(oldSource + i, m + 1) );
	    newNumbers.append( QCString(newSource + j, n + 1) );
	    i += m;
	    j += n;
	    met[k] = FALSE;
	    matchedYet[k] = 0;
	    k++;
	}
    }

    /*
      We now go over the old translation, "XeT 3.0", one letter at a
      time, looking for numbers found in oldNumbers. Whenever such a
      number is met, it is replaced with its newNumber equivalent. In
      our example, the "3.0" of "XeT 3.0" becomes "3.1".
    */
    for ( i = 0; i < (int) oldTranslation.length(); i++ ) {
	attempt += oldTranslation[i];
	for ( k = 0; k < p; k++ ) {
	    if ( oldTranslation[i] == oldNumbers[k][matchedYet[k]] )
		matchedYet[k]++;
	    else
		matchedYet[k] = 0;
	}

	/*
	  Let's find out if the last character ended a match. We make
	  two passes over the data. In the first pass, we try to
	  match only numbers that weren't matched yet; if that fails,
	  the second pass does the trick. This is useful in some
	  suspicious cases, flagged below.
	*/
	for ( pass = 0; pass < 2; pass++ ) {
	    best = p; // an impossible value
	    for ( k = 0; k < p; k++ ) {
		if ( (!met[k] || pass > 0) &&
		     matchedYet[k] == (int) oldNumbers[k].length() &&
		     numberLength(oldTranslation.latin1() + (i + 1) -
				  matchedYet[k]) == matchedYet[k] ) {
		    // the longer the better
		    if ( best == p || matchedYet[k] > matchedYet[best] )
			best = k;
		}
	    }
	    if ( best != p ) {
		attempt.truncate( attempt.length() - matchedYet[best] );
		attempt += newNumbers[best];
		met[best] = TRUE;
		for ( k = 0; k < p; k++ )
		    matchedYet[k] = 0;
		break;
	    }
	}
    }

    /*
      We flag two kinds of suspicious cases. They are identified as
      such with comments such as "{2000?}" at the end.

      Example of the first kind: old source text "TeX 3.0" translated
      as "XeT 2.0" is flagged "TeX 2.0 {3.0?}", no matter what the
      new text is.
    */
    for ( k = 0; k < p; k++ ) {
	if ( !met[k] )
	    attempt += QString( " {" ) + newNumbers[k] + QString( "?}" );
    }

    /*
      Example of the second kind: "1 of 1" translated as "1 af 1",
      with new source text "1 of 2", generates "1 af 2 {1 or 2?}"
      because it's not clear which of "1 af 2" and "2 af 1" is right.
    */
    for ( k = 0; k < p; k++ ) {
	for ( ell = 0; ell < p; ell++ ) {
	    if ( k != ell && oldNumbers[k] == oldNumbers[ell] &&
		    newNumbers[k] < newNumbers[ell] )
		attempt += QString( " {" ) + newNumbers[k] + QString( " or " ) +
			   newNumbers[ell] + QString( "?}" );
	}
    }
    return attempt;
}
コード例 #5
0
/*
 * This function operates on the assumption that each
 * field is of type java/lang/String.
 */
QAndroidJniObject valueForStaticField(JavaNames javaName, JavaNames javaFieldName)
{
    //construct key
    //the switch statements are used to reduce the number of duplicated strings
    //in the library

    const char* className;
    switch (javaName) {
    case JavaNames::BluetoothAdapter:
        className = javaBluetoothAdapterClassName; break;
    case JavaNames::BluetoothDevice:
        className = javaBluetoothDeviceClassName; break;
    default:
        qCWarning(QT_BT_ANDROID) << "Unknown java class name passed to valueForStaticField():" << javaName;
        return QAndroidJniObject();
    }

    const char *fieldName;
    switch (javaFieldName) {
    case JavaNames::ActionAclConnected:
        fieldName = javaActionAclConnected; break;
    case JavaNames::ActionAclDisconnected:
        fieldName = javaActionAclDisconnected; break;
    case JavaNames::ActionBondStateChanged:
        fieldName = javaActionBondStateChanged; break;
    case JavaNames::ActionDiscoveryStarted:
        fieldName = javaActionDiscoveryStarted; break;
    case JavaNames::ActionDiscoveryFinished:
        fieldName = javaActionDiscoveryFinished; break;
    case JavaNames::ActionFound:
        fieldName = javaActionFound; break;
    case JavaNames::ActionPairingRequest:
        fieldName = javaActionPairingRequest; break;
    case JavaNames::ActionScanModeChanged:
        fieldName = javaActionScanModeChanged; break;
    case JavaNames::ActionUuid:
        fieldName = javaActionUuid; break;
    case JavaNames::ExtraBondState:
        fieldName = javaExtraBondState; break;
    case JavaNames::ExtraDevice:
        fieldName = javaExtraDevice; break;
    case JavaNames::ExtraPairingKey:
        fieldName = javaExtraPairingKey; break;
    case JavaNames::ExtraPairingVariant:
        fieldName = javaExtraPairingVariant; break;
    case JavaNames::ExtraRssi:
        fieldName = javaExtraRssi; break;
    case JavaNames::ExtraScanMode:
        fieldName = javaExtraScanMode; break;
    case JavaNames::ExtraUuid:
        fieldName = javaExtraUuid; break;
    default:
        qCWarning(QT_BT_ANDROID) << "Unknown java field name passed to valueForStaticField():" << javaFieldName;
        return QAndroidJniObject();
    }

    int offset_class = qstrlen(className);
    int offset_field = qstrlen(fieldName);
    QByteArray key(offset_class + offset_field, Qt::Uninitialized);
    memcpy(key.data(), className, offset_class);
    memcpy(key.data()+offset_class, fieldName, offset_field);

    JCachedStringFields::iterator it = cachedStringFields()->find(key);
    if (it == cachedStringFields()->end()) {
        QAndroidJniEnvironment env;
        QAndroidJniObject fieldValue = QAndroidJniObject::getStaticObjectField(
                                            className, fieldName, "Ljava/lang/String;");
        if (env->ExceptionCheck()) {
            env->ExceptionDescribe();
            env->ExceptionClear();
            cachedStringFields()->insert(key, QAndroidJniObject());
            return QAndroidJniObject();
        }

        cachedStringFields()->insert(key, fieldValue);
        return fieldValue;
    } else {
        return it.value();
    }
}
コード例 #6
0
ファイル: main.cpp プロジェクト: agnousse/netglub
int main(int argc, char *argv[])
{
  NtgDaemon daemon(argc, argv);

  int option_index = 0;
  int c = 0;

  QString transformDirPath = "./transforms/";
  QString pluginsDirPath = "./plugins/";
  while ((c=getopt_long(argc, argv, "t:u:", long_options, &option_index)) != -1)
  {
    switch (c)
    {
      case 't':
      {
        transformDirPath = optarg;
        break;
      }
      case 'u':
      {
        pluginsDirPath = optarg;
        break;
      }
    }
    option_index = 0;
  }

  if( optind+3 >= argc )
  {
    QString appName = QFileInfo(argv[0]).completeBaseName();
    fprintf(stderr,"Usage: %s [-u <plugins dir> |-t <xml dir> ] <transform> "
            "<input: <type> (<name> <val>)+ > [ \"\" <params...>]\n",
            qPrintable(appName));
    exit(1);
  }

  QString transformType = QString::fromLocal8Bit(argv[optind]);
  NtgEntity entity;
  entity.type = argv[optind+1];
  int offset = optind + 2;
  for(; offset + 1 < argc && qstrlen(argv[offset]) != 0; offset += 2)
    entity.values[QString::fromLocal8Bit(argv[offset])] = QString::fromLocal8Bit(argv[offset+1]);

  QHash<QString,QString> params;
  if( qstrlen(argv[offset]) == 0 )
  {
    offset++;
    for(; offset + 1 < argc; offset += 2)
      params[QString::fromLocal8Bit(argv[offset])] = QString::fromLocal8Bit(argv[offset+1]);
  }

  qDebug() << entity;
  qDebug() << params;

  daemon.daemonize();
  NtgTransformManager manager(transformDirPath, pluginsDirPath, NULL);
  NtgTransform * t = manager.createTransformFromType(transformType);
  if( ! t )
    qFatal("No such transform: %s", qPrintable(transformType));

  QObject::connect(t, SIGNAL(statusChanged(Ntg::TransformStatus)), &daemon, SLOT(quit()));
  t->exec(entity, params);

  return daemon.exec();
}
コード例 #7
0
ファイル: proitems.cpp プロジェクト: RSATom/Qt
ProString::ProString(const char *str) :
    m_string(QString::fromLatin1(str)), m_offset(0), m_length(qstrlen(str)), m_file(0), m_hash(0x80000000)
{
}
コード例 #8
0
int idaapi emu()
{
    char szLabel[MAXSTR];
    insn_t saved;
    segment_t* pSegment;
    ea_t ea, length, offset;
    flags_t flags;
    uint32 dwFeature, i;

    dwFeature = cmd.get_canon_feature();
    fFlow = !(dwFeature & CF_STOP);

    if (dwFeature & CF_USE1) op_emu(cmd.Op1, 1);
    if (dwFeature & CF_USE2) op_emu(cmd.Op2, 1);

    if (dwFeature & CF_CHG1) op_emu(cmd.Op1, 0);
    if (dwFeature & CF_CHG2) op_emu(cmd.Op2, 0);

    saved = cmd;
    switch (cmd.itype)
    {
    case M8B_MOV:
        if (!cmd.Op1.is_reg(rPSP))
            break;
    case M8B_SWAP:
        if (cmd.itype == M8B_SWAP && !cmd.Op2.is_reg(rDSP))
            break;

        for (i = 0; i < 5; ++i)
        {
            ea = decode_prev_insn(cmd.ea);
            if (ea == BADADDR) break;
            if (cmd.itype == M8B_MOV && cmd.Op1.is_reg(rA) && cmd.Op2.type == o_imm)
            {
                ea = toRAM(cmd.Op2.value);
                if (ea != BADADDR)
                {
                    qsnprintf(szLabel, sizeof(szLabel), "%s_%0.2X", cmd.itype == M8B_MOV ? "psp" : "dsp", cmd.Op2.value);
                    ua_add_dref(cmd.Op2.offb, ea, dr_O);
                    set_name(ea, szLabel, SN_NOWARN);
                }
                break;
            }
        }
        break;
    case M8B_JACC:
        pSegment = getseg(cmd.ea);
        if (!pSegment) break;
        length = pSegment->endEA - cmd.ea;
        if (length > 256) length = 256;
        for (offset = 2; offset < length; offset += 2)
        {
            ea = toROM(saved.Op1.addr + offset);
            if (ea == BADADDR) break;
            flags = getFlags(ea);
            if (!hasValue(flags) || (has_any_name(flags) || hasRef(flags)) || !create_insn(ea)) break;
            switch (cmd.itype)
            {
            case M8B_JMP:
            case M8B_RET:
            case M8B_RETI:
            case M8B_IPRET:
                add_cref(saved.ea, ea, fl_JN);
                break;
            default:
                offset = length;
            }
        }
        break;
    case M8B_IORD:
    case M8B_IOWR:
    case M8B_IOWX:
        for (i = 0; i < 5; ++i)
        {
            ea = (saved.itype == M8B_IORD) ? decode_insn(cmd.ea + cmd.size) : decode_prev_insn(cmd.ea);
            if (ea == BADADDR) break;
            if (cmd.Op1.is_reg(rA) && cmd.Op2.type == o_imm)
            {
                qsnprintf(szLabel, sizeof(szLabel), "[A=%0.2Xh] ", cmd.Op2.value);
                if (get_portbits_sym(szLabel + qstrlen(szLabel), saved.Op1.addr, cmd.Op2.value))
                    set_cmt(saved.ea, szLabel, false);
                break;
            }
        }
    }
    cmd = saved;

    if ((cmd.ea & 0xFF) == 0xFF)
    {
        switch (cmd.itype)
        {
        case M8B_RET:
        case M8B_RETI:
        case M8B_XPAGE:
            break;
        default:
            QueueMark(Q_noValid, cmd.ea);
        }
    }

    if (fFlow) ua_add_cref(0, cmd.ea + cmd.size, fl_F);

    return 1;
}
コード例 #9
0
ファイル: packagemodel.cpp プロジェクト: deiv/plasmate-pkg
QVariant PackageModel::data(const QModelIndex &index, int role) const
{
    if (!m_package || !index.isValid()) {
        return QVariant();
    }

    QModelIndex parentIndex = parent(index);

    const char *key = static_cast<const char *>(index.internalPointer());
    if (key) {
        // we have a child item
        switch (role) {
        case MimeTypeRole: {
            if (index.row() == 0) {
                if(!qstrcmp(key, "animations") && packageType() != "Plasma/Theme") {
                    //add an exception. the plasmoid package also contains the key animations,
                    //so if this isn't a theme package return the right mimetype
                    return QStringList("[plasmate]/new");
                } else if (m_dialogOptions.contains(key)) {
                    return m_dialogOptions.value(key);
                }
                return QStringList("[plasmate]/new");
            }

            const char *imagePrefix = "[plasmate]/themeImageDialog/";
            if (!qstrcmp(key, "images") || !qstrncmp(key, imagePrefix, qstrlen(imagePrefix))) {
                return QStringList("[plasmate]/imageViewer");
            }

            if (!qstrcmp(key, "config")) {
                return QStringList("[plasmate]/kconfigxteditor");
            }
            return m_package->structure()->mimetypes(key);
        }
        break;
        case UrlRole: {
            return urlForIndex(index).pathOrUrl();
        }
        break;
        case Qt::DisplayRole: {
            if (index.row() == 0) {
                if (!qstrcmp(m_topEntries.at(parentIndex.row()), "config") &&
                    !fileExists("mainconfigxml")) {
                    return i18n("New configuration XML file");
                }
                return i18n("New...");
            }

            QList<const char *> named = m_namedFiles.value(key);
            int row = index.row() - 1;
            if (row < named.count()) {
                //kDebug() << m_package->structure()->name(named.at(row));
                return m_package->structure()->name(named.at(row));
            }
            row -= named.count();
            QStringList l = m_files.value(key);
            if (row < l.count()) {
                //kDebug() << "got" << l.at(index.row() - 1);
                return l.at(row);
            }
        }
        break;
        case PackagePathRole: {
            return m_package ? m_package->path() : QString();
        }
        case Qt::DecorationRole: {
            if (index.row() == 0) {
                return KIcon("document-new");
            } else {
                return KIcon(KMimeType::iconNameForUrl(urlForIndex(index)));
            }
        }
        break;
        case ContentsWithSubdirRole: {
            return contentsWithSubdirRole(parentIndex.row());
        }
        }
    } else {
        // it's a top level item
        //kDebug() << "data for top level item" << index.row() << m_topEntries.count() << role << Qt::DisplayRole;
        switch (role) {
        case Qt::DisplayRole: {
            if (index.row() == m_topEntries.count()) {
                return i18n("Metadata");
            }

            return m_structure->name(m_topEntries.at(index.row()));
        }

        break;
        case MimeTypeRole: {
            if (index.row() + 1  == m_topEntries.count()) {
               if (packageType() == "Plasma/Theme") {
                    //kcolorscheme will share the same index for creating and read/write
                    if (!fileExists("colors")) {
                        return QStringList("[plasmate]/kcolorscheme");
                    } else {
                        return m_package->structure()->mimetypes("colors");
                    }
                } else if (packageType() == "Plasma/Applet") {
                    if (!fileExists("mainconfigui")) {
                        return QStringList("[plasmate]/mainconfigui");
                    }
                }
            }

            if (index.row() == m_topEntries.count()) {
                return QStringList("[plasmate]/metadata");
            }
        }
        break;
        case UrlRole: {
            if (index.row() == m_topEntries.count()) {
                return m_package->path() + "metadata.desktop";
            }

            if (index.row() + 1  == m_topEntries.count()) {
                if (m_package) {
                    return m_package->path() + contentsWithSubdirRole(index.row());
                }
            }

            return QString();
        }
        break;
        case PackagePathRole: {
            return m_package ? m_package->path() : QString();
        }
        break;
        case ContentsWithSubdirRole: {
            return contentsWithSubdirRole(index.row());
        }
        }
    }
    return QVariant();
}
コード例 #10
0
ファイル: proitems.cpp プロジェクト: RSATom/Qt
ProString::ProString(const char *str, DoPreHashing) :
    m_string(QString::fromLatin1(str)), m_offset(0), m_length(qstrlen(str)), m_file(0)
{
    updatedHash();
}
void QSGSharedDistanceFieldGlyphCache::saveTexture(GLuint textureId, int width, int height)
{
    GLuint fboId;
    glGenFramebuffers(1, &fboId);

    GLuint tmpTexture = 0;
    glGenTextures(1, &tmpTexture);
    glBindTexture(GL_TEXTURE_2D, tmpTexture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glBindTexture(GL_TEXTURE_2D, 0);

    glBindFramebuffer(GL_FRAMEBUFFER_EXT, fboId);
    glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D,
                           tmpTexture, 0);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, textureId);

    glDisable(GL_STENCIL_TEST);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_SCISSOR_TEST);
    glDisable(GL_BLEND);

    GLfloat textureCoordinateArray[8];
    textureCoordinateArray[0] = 0.0f;
    textureCoordinateArray[1] = 0.0f;
    textureCoordinateArray[2] = 1.0f;
    textureCoordinateArray[3] = 0.0f;
    textureCoordinateArray[4] = 1.0f;
    textureCoordinateArray[5] = 1.0f;
    textureCoordinateArray[6] = 0.0f;
    textureCoordinateArray[7] = 1.0f;

    GLfloat vertexCoordinateArray[8];
    vertexCoordinateArray[0] = -1.0f;
    vertexCoordinateArray[1] = -1.0f;
    vertexCoordinateArray[2] =  1.0f;
    vertexCoordinateArray[3] = -1.0f;
    vertexCoordinateArray[4] =  1.0f;
    vertexCoordinateArray[5] =  1.0f;
    vertexCoordinateArray[6] = -1.0f;
    vertexCoordinateArray[7] =  1.0f;

    glViewport(0, 0, width, height);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, vertexCoordinateArray);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinateArray);

    {
        static const char vertexShaderSource[] =
                "attribute highp   vec4      vertexCoordsArray; \n"
                "attribute highp   vec2      textureCoordArray; \n"
                "varying   highp   vec2      textureCoords;     \n"
                "void main(void) \n"
                "{ \n"
                "    gl_Position = vertexCoordsArray;   \n"
                "    textureCoords = textureCoordArray; \n"
                "} \n";

        static const char fragmentShaderSource[] =
                "varying   highp   vec2      textureCoords; \n"
                "uniform   sampler2D         texture;       \n"
                "void main() \n"
                "{ \n"
                "    gl_FragColor = texture2D(texture, textureCoords); \n"
                "} \n";

        GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
        GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);

        if (vertexShader == 0 || fragmentShader == 0) {
            GLenum error = glGetError();
            qWarning("SharedGraphicsCacheServer::setupShaderPrograms: Failed to create shaders. (GL error: %x)",
                     error);
            return;
        }

        glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
        glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
        glCompileShader(vertexShader);

        GLint len = 1;
        glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &len);

        char infoLog[2048];
        glGetShaderInfoLog(vertexShader, 2048, NULL, infoLog);
        if (qstrlen(infoLog) > 0) {
            qWarning("SharedGraphicsCacheServer::setupShaderPrograms, problems compiling vertex shader:\n %s",
                     infoLog);
            //return;
        }

        glCompileShader(fragmentShader);
        glGetShaderInfoLog(fragmentShader, 2048, NULL, infoLog);
        if (qstrlen(infoLog) > 0) {
            qWarning("SharedGraphicsCacheServer::setupShaderPrograms, problems compiling fragent shader:\n %s",
                     infoLog);
            //return;
        }

        GLuint shaderProgram = glCreateProgram();
        glAttachShader(shaderProgram, vertexShader);
        glAttachShader(shaderProgram, fragmentShader);

        glBindAttribLocation(shaderProgram, 0, "vertexCoordsArray");
        glBindAttribLocation(shaderProgram, 1, "textureCoordArray");

        glLinkProgram(shaderProgram);
        glGetProgramInfoLog(shaderProgram, 2048, NULL, infoLog);
        if (qstrlen(infoLog) > 0) {
            qWarning("SharedGraphicsCacheServer::setupShaderPrograms, problems linking shaders:\n %s",
                     infoLog);
            //return;
        }

        glUseProgram(shaderProgram);
        glEnableVertexAttribArray(0);
        glEnableVertexAttribArray(1);

        int textureUniformLocation = glGetUniformLocation(shaderProgram, "_qt_texture");
        glUniform1i(textureUniformLocation, 0);
    }

    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

    {
        GLenum error = glGetError();
        if (error != GL_NO_ERROR) {
            qWarning("SharedGraphicsCacheServer::readBackBuffer: glDrawArrays reported error 0x%x",
                     error);
        }
    }

    uchar *data = new uchar[width * height * 4];

    glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data);

    QImage image(width, height, QImage::Format_ARGB32);
    quint32 *dest = reinterpret_cast<quint32 *>(image.bits());
    for (int i=0; i<width*height; ++i)
        dest[i] = qRgba(0xff, 0xff, 0xff, data[i]);

    QByteArray fileName = m_cacheId + ' ' + QByteArray::number(textureId);
    fileName = fileName.replace('/', '_').replace(' ', '_') + ".png";
    image.save(QString::fromLocal8Bit(fileName));

    {
        GLenum error = glGetError();
        if (error != GL_NO_ERROR) {
            qWarning("SharedGraphicsCacheServer::readBackBuffer: glReadPixels reported error 0x%x",
                     error);
        }
    }

    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);

    glDeleteFramebuffers(1, &fboId);
    glDeleteTextures(1, &tmpTexture);

    delete[] data;
}
コード例 #12
0
ファイル: 3DControls.cpp プロジェクト: pvaut/Z-Flux
void T3DControl_Menu::rendermenu(T3DControl_Menu_Item *parentitem, Trendercontext *rc, double x0, double y0)
{
	StrPtr texturename=G_texturename();
	T3DTexture *texture=NULL;
	if (qstrlen(texturename)>0)
	{
		texture=parentframe->G_texture(texturename);
		if (texture==NULL)
		{
			QString errstr;FormatString(errstr,_text("Could not find texture '^1'"),texturename);
			throw QError(errstr);
		}
	}

	TQXColor col_foreground(rendercolor.G_R(),rendercolor.G_G(),rendercolor.G_B(),rendercolor.G_A());

	TSC_color *backcol=G_scene()->G_backcolor();
	TQXColor col_background(backcol->G_R(),backcol->G_G(),backcol->G_B(),backcol->G_A());

	TQXColor col_menuback=6*col_background+col_foreground;


	TQXColor col_sel=TQXColor(0,0.7,0);

	TQXColor col_menubacksel=1.5*col_background+col_foreground;

	TQXColor col_menubackactivesel=col_menubacksel+1.5*col_sel;

	if (texture!=NULL)
	{
		col_menuback=col_foreground;
		col_menubacksel=col_foreground;
		col_menubackactivesel=col_sel;
	}


	double z0=G_offset();
	double sx=sizex->G_val();
	double yp=y0;
	for (int i=0; i<parentitem->subitems.G_count(); i++)
	{
		T3DControl_Menu_Item *item=parentitem->subitems[i];
		double lineh=GetItemH(*item);

		TQXColor cl1=col_menuback;
		if (i==parentitem->cursubsel)
		{
			cl1=col_menubacksel;
			if (G_isactive())
				cl1=col_menubackactivesel;
		}

		TQXColor cl2=cl1;
		if (texture==NULL)
			cl2=cl1.IntensIncr(0.10)+0.05*TQXColor(0.0,1.0,0.0);
		cl1.set(cl1.G_r(),cl1.G_g(),cl1.G_b(),col_foreground.G_a());
		cl2.set(cl2.G_r(),cl2.G_g(),cl2.G_b(),col_foreground.G_a());

		if (texture!=NULL) texture->select(rc);
		render_rect2(rc,x0,yp-lineh,sx,lineh,z0,cl1,cl2);
		if (texture!=NULL) texture->unselect(rc);

		if (!item->IsSeparator())
		{
			rc->set_color(0,0,0,col_foreground.G_a());
			rc->rendertext(DEFAULT_FONT,&Tvertex(x0+0.7*lineh+G_textsize()/15,yp-lineh+lineh/4-G_textsize()/15,z0+G_offset()/2),
				&Tvector(G_textsize(),0,0),
				&Tvector(0,G_textsize(),0),item->name,0);

			rc->set_color(col_foreground.G_r(),col_foreground.G_g(),col_foreground.G_b(),col_foreground.G_a());
			rc->rendertext(DEFAULT_FONT,&Tvertex(x0+0.7*lineh,yp-lineh+lineh/4,z0+G_offset()),
				&Tvector(G_textsize(),0,0),
				&Tvector(0,G_textsize(),0),item->name,0);
		}
		else
		{
			rc->set_color(col_foreground.G_r(),col_foreground.G_g(),col_foreground.G_b(),col_foreground.G_a());
			//render_rect(rc,x0,yp,sx,lineh/3,z0+G_offset());
			render_rect2(rc,x0,yp-lineh/2-lineh/6,sx,lineh/3,z0+G_offset(),3*col_foreground+col_menuback,6*col_foreground+col_menuback);
		}

		if (item->checked)
		{
			double oo=lineh/8;
			glLineWidth(2.0f);
			glBegin(GL_LINE_STRIP);
			glVertex3d(x0+lineh/4-oo,yp-lineh+0.4*lineh+oo,z0+G_offset());
			glVertex3d(x0+lineh/4,yp-lineh+0.4*lineh,z0+G_offset());
			glVertex3d(x0+lineh/4+2*oo,yp-lineh+0.4*lineh+2*oo,z0+G_offset());
			glEnd();
		}

		if (item->subitems.G_count()>0)
		{
			double oo=lineh/4;
//			glLineWidth(2.0f);
			glBegin(GL_TRIANGLES);
			glVertex3d(x0+sx-oo/2-oo,yp-lineh+lineh/2-oo,z0+G_offset());
			glVertex3d(x0+sx-oo/2,yp-lineh+lineh/2,z0+G_offset());
			glVertex3d(x0+sx-oo/2-oo,yp-lineh+lineh/2+oo,z0+G_offset());
			glEnd();
		}

		if (i==parentitem->cursubsel) rendermenu(item,rc,x0+sx+lineh/10,yp);

		yp-=lineh;
	}
}
コード例 #13
0
ファイル: crypto.cpp プロジェクト: hccde/fibjs
char *randomart(const unsigned char *dgst_raw, size_t dgst_raw_len,
                const char *title, int32_t size)
{
    const char augmentation_string[] = " .o+=*BOX@%&#/^SE";
    char *retval, *p;
    unsigned char *field;
    int32_t i, b, n;
    int32_t x, y;
    const size_t len = sizeof(augmentation_string) - 2;
    int32_t fieldY = size + 1;
    int32_t fieldX = size * 2 + 1;

    retval = (char *)calloc(1, (fieldX + 3) * (fieldY + 2));
    if (retval == NULL)
        return NULL;

    field = (unsigned char *)calloc(1, fieldX * fieldY);
    x = fieldX / 2;
    y = fieldY / 2;

    for (i = 0; i < (int32_t)dgst_raw_len; i++)
    {
        int32_t input;

        input = dgst_raw[i];
        for (b = 0; b < 4; b++)
        {
            x += (input & 0x1) ? 1 : -1;
            y += (input & 0x2) ? 1 : -1;

            x = _max(x, 0);
            y = _max(y, 0);
            x = _min(x, fieldX - 1);
            y = _min(y, fieldY - 1);

            if (field[x * fieldY + y] < len - 2)
                field[x * fieldY + y]++;
            input = input >> 2;
        }
    }

    field[(fieldX / 2) * fieldY + fieldY / 2] = len - 1;
    field[x * fieldY + y] = len;

    p = retval;
    *p++ = '+';
    for (i = 0; i < fieldX; i++)
        *p++ = '-';
    *p++ = '+';
    *p++ = '\n';

    n = (int32_t)qstrlen(title);
    if (n > 0)
    {
        if ( n > fieldX - 2)
            n = fieldX - 2;
        p = retval + (fieldX - n) / 2;

        *p++ = '[';
        memcpy(p, title, n);
        p += n;
        *p++ = ']';
        p = retval + fieldX + 3;
    }

    for (y = 0; y < fieldY; y++)
    {
        *p++ = '|';
        for (x = 0; x < fieldX; x++)
            *p++ = augmentation_string[_min(field[x * fieldY + y], len)];
        *p++ = '|';
        *p++ = '\n';
    }

    *p++ = '+';
    for (i = 0; i < fieldX; i++)
        *p++ = '-';
    *p++ = '+';

    free(field);

    return retval;
}
コード例 #14
0
void HttpUploadCollection::parse(exlib::string& str, const char* boundary)
{
    const char* pstr = str.c_str();
    int32_t nSize = (int32_t)str.length();
    exlib::string strName;
    exlib::string strFileName;
    exlib::string strContentType;
    exlib::string strContentTransferEncoding;
    const char *p, *p1, *p2, *szQueryString;
    const char* pstrSplit;
    int32_t uiSplitSize;
    char ch;

    boundary += 20;
    while (*boundary && *boundary == ' ')
        boundary++;

    if (qstricmp(boundary, "boundary=", 9))
        return;

    boundary += 9;
    uiSplitSize = (int32_t)qstrlen(boundary);

    pstrSplit = szQueryString = pstr;

    if (nSize < uiSplitSize + 2 || szQueryString[0] != '-'
        || szQueryString[1] != '-'
        || qstrcmp(szQueryString + 2, boundary, uiSplitSize))
        return;

    uiSplitSize += 2;
    szQueryString += uiSplitSize;
    nSize -= uiSplitSize;

    while (nSize) {
        strFileName.clear();
        strContentType.clear();
        strContentTransferEncoding.clear();

        while (nSize > 0) {
            ch = *szQueryString++;
            nSize--;
            if (ch != '\r')
                return;
            if (nSize > 0 && *szQueryString == '\n') {
                nSize--;
                szQueryString++;
            }

            p = szQueryString;
            while (nSize > 0 && *p != '\r') {
                nSize--;
                p++;
            }

            if (nSize == 0)
                break;

            p1 = szQueryString;
            szQueryString = p;

            if (p != p1) {
                if (p1 + 20 < p && !qstricmp(p1, "Content-Disposition:", 20)) {
                    p1 += 20;
                    while (p1 < p && *p1 == ' ')
                        p1++;
                    if (p1 + 10 >= p || qstricmp(p1, "form-data;", 10))
                        return;

                    p1 += 10;
                    while (p1 < p && *p1 == ' ')
                        p1++;
                    if (p1 + 5 >= p || qstricmp(p1, "name=", 5))
                        return;

                    p1 += 5;

                    while (p1 < p && *p1 == ' ')
                        p1++;

                    ch = ';';
                    if (*p1 == '\"') {
                        p1++;
                        ch = '\"';
                    }

                    p2 = p1;
                    while (p1 < p && *p1 != ch)
                        p1++;

                    strName.assign(p2, (int32_t)(p1 - p2));

                    if (p1 < p && *p1 == '\"')
                        p1++;

                    if (p1 < p && *p1 == ';')
                        p1++;

                    while (p1 < p && *p1 == ' ')
                        p1++;

                    if (p1 + 9 < p && !qstricmp(p1, "filename=", 9)) {
                        p1 += 9;

                        while (p1 < p && *p1 == ' ')
                            p1++;

                        ch = ';';
                        if (*p1 == '\"') {
                            p1++;
                            ch = '\"';
                        }

                        p2 = p1;
                        while (p1 < p && *p1 != ch) {
                            if (*p1 == '/' || *p1 == '\\')
                                p2 = p1 + 1;
                            p1++;
                        }

                        strFileName.assign(p2, (int32_t)(p1 - p2));
                    }
                } else if (p1 + 13 < p && !qstricmp(p1, "Content-Type:", 13)) {
                    p1 += 13;
                    while (p1 < p && *p1 == ' ')
                        p1++;
                    strContentType.assign(p1, (int32_t)(p - p1));
                } else if (p1 + 26 < p && !qstricmp(p1, "Content-Transfer-Encoding:", 26)) {
                    p1 += 26;
                    while (p1 < p && *p1 == ' ')
                        p1++;
                    strContentTransferEncoding.assign(p1, (int32_t)(p - p1));
                }
            } else {
                ch = *szQueryString++;
                nSize--;
                if (ch != '\r')
                    return;
                if (nSize > 0 && *szQueryString == '\n') {
                    nSize--;
                    szQueryString++;
                }
                break;
            }
        }

        p = szQueryString;
        p1 = p + nSize;
        while (p1 > p && (p = (char*)memchr(p, '-', p1 - p))
            && p1 > p + uiSplitSize && memcmp(p, pstrSplit, uiSplitSize))
            p++;

        if (!p || p1 <= p + uiSplitSize)
            break;

        nSize = (int32_t)(p1 - p - uiSplitSize);
        p1 = szQueryString;
        szQueryString = p + uiSplitSize;

        if (p > p1) {
            p--;
            ch = *p;
            if (ch != '\n')
                return;

            if (p > p1 && *(p - 1) == '\r')
                p--;
        }

        if (!strName.empty()) {
            int32_t uiSize = (int32_t)(p - p1);
            exlib::string strTemp;
            Variant varTemp;

            strTemp.assign(p1, uiSize);

            if (strFileName.empty())
                varTemp = strTemp;
            else {
                obj_ptr<HttpUploadData> objTemp = new HttpUploadData();
                date_t tm;

                objTemp->m_name = strFileName;
                objTemp->m_type = strContentType;
                objTemp->m_encoding = strContentTransferEncoding;
                objTemp->m_body = new MemoryStream::CloneStream(strTemp, tm);

                varTemp = objTemp;
            }

            add(strName, varTemp);
        }
    }
}
コード例 #15
0
ファイル: qtextcodec.cpp プロジェクト: cedrus/qt
/*!
    \overload

    \a chars contains the source characters.
*/
QString QTextCodec::toUnicode(const char *chars) const
{
    int len = qstrlen(chars);
    return convertToUnicode(chars, len, 0);
}
コード例 #16
0
ファイル: definition.cpp プロジェクト: kevinoupeng/mydg
/*! Reads a fragment of code from file \a fileName starting at 
 * line \a startLine and ending at line \a endLine (inclusive). The fragment is
 * stored in \a result. If FALSE is returned the code fragment could not be
 * found.
 *
 * The file is scanned for a opening bracket ('{') from \a startLine onward
 * The line actually containing the bracket is returned via startLine.
 * The file is scanned for a closing bracket ('}') from \a endLine backward.
 * The line actually containing the bracket is returned via endLine.
 * Note that for VHDL code the bracket search is not done.
 */
bool readCodeFragment(const char *fileName,
                      int &startLine,int &endLine,QCString &result)
{
  static bool filterSourceFiles = Config_getBool("FILTER_SOURCE_FILES");
  static int tabSize = Config_getInt("TAB_SIZE");
  //printf("readCodeFragment(%s,%d,%d)\n",fileName,startLine,endLine);
  if (fileName==0 || fileName[0]==0) return FALSE; // not a valid file name
  QCString filter = getFileFilter(fileName,TRUE);
  FILE *f=0;
  bool usePipe = !filter.isEmpty() && filterSourceFiles;
  SrcLangExt lang = getLanguageFromFileName(fileName);
  if (!usePipe) // no filter given or wanted
  {
    f = portable_fopen(fileName,"r");
  }
  else // use filter
  {
    QCString cmd=filter+" \""+fileName+"\"";
    Debug::print(Debug::ExtCmd,0,"Executing popen(`%s`)\n",cmd.data());
    f = portable_popen(cmd,"r");
  }
  bool found = lang==SrcLangExt_VHDL   || 
               lang==SrcLangExt_Tcl    || 
               lang==SrcLangExt_Python || 
               lang==SrcLangExt_Fortran;  
               // for VHDL, TCL, Python, and Fortran no bracket search is possible
  if (f)
  {
    int c=0;
    int col=0;
    int lineNr=1;
    // skip until the startLine has reached
    while (lineNr<startLine && !feof(f))
    {
      while ((c=fgetc(f))!='\n' && c!=EOF) /* skip */;
      lineNr++; 
      if (found && c == '\n') c = '\0';
    }
    if (!feof(f))
    {
      // skip until the opening bracket or lonely : is found
      char cn=0;
      while (lineNr<=endLine && !feof(f) && !found)
      {
        int pc=0;
        while ((c=fgetc(f))!='{' && c!=':' && c!=EOF)  // } so vi matching brackets has no problem
        {
          //printf("parsing char `%c'\n",c);
          if (c=='\n') 
          {
            lineNr++,col=0; 
          }
          else if (c=='\t') 
          {
            col+=tabSize - (col%tabSize);
          }
          else if (pc=='/' && c=='/') // skip single line comment
          {
            while ((c=fgetc(f))!='\n' && c!=EOF) pc=c;
            if (c=='\n') lineNr++,col=0;
          }
          else if (pc=='/' && c=='*') // skip C style comment
          {
            while (((c=fgetc(f))!='/' || pc!='*') && c!=EOF) 
            {
              if (c=='\n') lineNr++,col=0;
              pc=c;
            }
          }
          else
          {
            col++;
          }
          pc = c;
        }
        if (c==':')
        {
          cn=fgetc(f);
          if (cn!=':') found=TRUE;
        }
        else if (c=='{')   // } so vi matching brackets has no problem
        {
          found=TRUE;
        }
      }
      //printf(" -> readCodeFragment(%s,%d,%d) lineNr=%d\n",fileName,startLine,endLine,lineNr);
      if (found) 
      {
        // For code with more than one line,
        // fill the line with spaces until we are at the right column
        // so that the opening brace lines up with the closing brace
        if (endLine!=startLine)
        {
          QCString spaces;
          spaces.fill(' ',col);
          result+=spaces;
        }
        // copy until end of line
        if (c) result+=c;
        startLine=lineNr;
        if (c==':') 
        {
          result+=cn;
          if (cn=='\n') lineNr++;
        }
        const int maxLineLength=4096;
        char lineStr[maxLineLength];
        do 
        {
          //printf("reading line %d in range %d-%d\n",lineNr,startLine,endLine);
          int size_read;
          do 
          {
            // read up to maxLineLength-1 bytes, the last byte being zero
            char *p = fgets(lineStr, maxLineLength,f);
            //printf("  read %s",p);
            if (p) 
            {
              size_read=qstrlen(p); 
            }
            else  // nothing read
            {
              size_read=-1;
              lineStr[0]='\0';
            }
            result+=lineStr;
          } while (size_read == (maxLineLength-1));

          lineNr++; 
        } while (lineNr<=endLine && !feof(f));

        // strip stuff after closing bracket
        int newLineIndex = result.findRev('\n');
        int braceIndex   = result.findRev('}');
        if (braceIndex > newLineIndex) 
        {
          result.truncate(braceIndex+1);
        }
        endLine=lineNr-1;
      }
    }
    if (usePipe) 
    {
      portable_pclose(f); 
      Debug::print(Debug::FilterOutput, 0, "Filter output\n");
      Debug::print(Debug::FilterOutput,0,"-------------\n%s\n-------------\n",result.data());
    }
    else 
    {
      fclose(f);
    }
  }
  result = transcodeCharacterStringToUTF8(result);
  //fprintf(stderr,"readCodeFragement(%d-%d)=%s\n",startLine,endLine,result.data());
  return found;
}
コード例 #17
0
ファイル: 3DGeoObjects.cpp プロジェクト: pvaut/Z-Flux
void T3DGeoObject::render(Trendercontext *rc, const TObjectRenderStatus *status, bool isrecording)
{
	QString nm;
	G_name(nm);

	if (!G_isvisible(rc)) return;

	//transparency, blend type & depth mask logic
	int currentobjectblendtype=status->currentobjectblendtype;
	if (blendtype->toint()!=BlendNormal) currentobjectblendtype=blendtype->toint();
	int currentdepthmask=status->currentobjectdepthmask;
	if (depthmask->toint()!=DepthMaskNormal) currentdepthmask=depthmask->toint();

	bool rendernow=false;
	if (!isbackground->G_val())
	{
		if ((rc->currentrenderpass==Trendercontext::RP_SOLID)&&(currentobjectblendtype==BlendNormal)) rendernow=true;
		if ((rc->currentrenderpass==Trendercontext::RP_TRANSPARENT)&&(currentobjectblendtype!=BlendNormal)) rendernow=true;
	}
	else
	{
		if (rc->currentrenderpass==Trendercontext::RP_SOLID) rendernow=true;
	}
	if (!rendernow) return;

	bool currentenablelight=status->enablelight;
	if (!enablelight->G_val()) currentenablelight=false;
	rc->SetBlendType(currentobjectblendtype);
	
	rc->EnableDepthMask(currentdepthmask!=DepthMaskDisable);

	int currentdepthtest=status->currentobjectdepthtest;
	if (depthtest->toint()!=DepthTestNormal) currentdepthtest=depthtest->toint();
	rc->EnableDepthTest(currentdepthtest!=DepthTestDisable);



	ASSERT(parentframe!=NULL);
	ASSERT(scene!=NULL);

	if (scene==NULL) throw QError(_text("No scene attached to object"));
	StrPtr texturename=G_texturename();
	if (rc->G_isrightwindow())
		if (qstrlen(G_texturenameright())>0)
			texturename=G_texturenameright();
	T3DTexture *texture=NULL;
	if (qstrlen(texturename)>0)
	{
		texture=parentframe->G_texture(texturename);
		if (texture==NULL)
		{
			QString errstr;FormatString(errstr,_text("Could not find texture '^1'"),texturename);
			throw QError(errstr);
		}
		texture->select(rc);
	}

	rc->set_color(rendercolor.G_R(),rendercolor.G_G(),rendercolor.G_B(),rendercolor.G_A());
	rc->set_speccolor(speccolor,specvalue->G_val());
	rc->set_orientation(+1);
	rc->enablelight(currentenablelight);

	Tvector transl;transl.copyfrom(*position);
	rc->create_subframe_translated(transl);

	if (renderoutline->G_val()) glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);

	if ((currentobjectblendtype==BlendTranslucent)&&(renderfront->G_val())&&(renderback->G_val()))
	{//two-sided objects with true transparency need to be drawn in a special way
		glEnable(GL_CULL_FACE);
		glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
		glCullFace(GL_FRONT);
		render_drawobject(rc,status,isrecording);
		glCullFace(GL_BACK);
		render_drawobject(rc,status,isrecording);
	}
	else
	{
		if ((renderfront->G_val())&&(renderback->G_val()))
		{
			glDisable(GL_CULL_FACE);
			glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
		}
		if ((renderfront->G_val())&&(!renderback->G_val()))
		{
			glEnable(GL_CULL_FACE);
			glCullFace(GL_BACK);
			glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_FALSE);
		}
		if ((!renderfront->G_val())&&(renderback->G_val()))
		{
			glEnable(GL_CULL_FACE);
			glCullFace(GL_FRONT);
			glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
		}
		if ((!renderfront->G_val())&&(!renderback->G_val())) return;
		render_drawobject(rc,status,isrecording);
	}

	if (renderoutline->G_val()) glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);

	if (texture!=NULL) texture->unselect(rc);

	rc->del_subframe();

	isdirty=false;
}
コード例 #18
0
ファイル: qxbmhandler.cpp プロジェクト: Afreeca/qt
static bool write_xbm_image(const QImage &sourceImage, QIODevice *device, const QString &fileName)
{
    QImage image = sourceImage;
    int	       w = image.width();
    int	       h = image.height();
    int	       i;
    QString    s = fileName; // get file base name
    int        msize = s.length() + 100;
    char *buf = new char[msize];

    qsnprintf(buf, msize, "#define %s_width %d\n", s.toAscii().data(), w);
    device->write(buf, qstrlen(buf));
    qsnprintf(buf, msize, "#define %s_height %d\n", s.toAscii().data(), h);
    device->write(buf, qstrlen(buf));
    qsnprintf(buf, msize, "static char %s_bits[] = {\n ", s.toAscii().data());
    device->write(buf, qstrlen(buf));

    if (image.format() != QImage::Format_MonoLSB)
        image = image.convertToFormat(QImage::Format_MonoLSB);

    bool invert = qGray(image.color(0)) < qGray(image.color(1));
    char hexrep[16];
    for (i=0; i<10; i++)
	hexrep[i] = '0' + i;
    for (i=10; i<16; i++)
	hexrep[i] = 'a' -10 + i;
    if (invert) {
	char t;
	for (i=0; i<8; i++) {
	    t = hexrep[15-i];
	    hexrep[15-i] = hexrep[i];
	    hexrep[i] = t;
	}
    }
    int bcnt = 0;
    register char *p = buf;
    int bpl = (w+7)/8;
    for (int y = 0; y < h; ++y) {
        uchar *b = image.scanLine(y);
        for (i = 0; i < bpl; ++i) {
            *p++ = '0'; *p++ = 'x';
            *p++ = hexrep[*b >> 4];
            *p++ = hexrep[*b++ & 0xf];

            if (i < bpl - 1 || y < h - 1) {
                *p++ = ',';
                if (++bcnt > 14) {
                    *p++ = '\n';
                    *p++ = ' ';
                    *p   = '\0';
                    if ((int)qstrlen(buf) != device->write(buf, qstrlen(buf))) {
                        delete [] buf;
                        return false;
                    }
                    p = buf;
                    bcnt = 0;
                }
            }
        }
    }
#if defined(_MSC_VER) && _MSC_VER >= 1400
    strcpy_s(p, sizeof(" };\n"), " };\n");
#else
    strcpy(p, " };\n");
#endif
    if ((int)qstrlen(buf) != device->write(buf, qstrlen(buf))) {
        delete [] buf;
        return false;
    }

    delete [] buf;
    return true;
}
コード例 #19
0
ファイル: syncengine.cpp プロジェクト: wkarl/client
int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote )
{
    if( ! file ) return -1;

    QTextCodec::ConverterState utf8State;
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    Q_ASSERT(codec);
    QString fileUtf8 = codec->toUnicode(file->path, qstrlen(file->path), &utf8State);
    QString renameTarget;
    QString key = fileUtf8;

    auto instruction = file->instruction;
    if (utf8State.invalidChars > 0 || utf8State.remainingChars > 0) {
        qWarning() << "File ignored because of invalid utf-8 sequence: " << file->path;
        instruction = CSYNC_INSTRUCTION_IGNORE;
    } else {
        renameTarget = codec->toUnicode(file->rename_path, qstrlen(file->rename_path), &utf8State);
        if (utf8State.invalidChars > 0 || utf8State.remainingChars > 0) {
            qWarning() << "File ignored because of invalid utf-8 sequence in the rename_path: " << file->path << file->rename_path;
            instruction = CSYNC_INSTRUCTION_IGNORE;
        }
        if (instruction == CSYNC_INSTRUCTION_RENAME) {
            key = renameTarget;
        }
    }

    // Gets a default-contructed SyncFileItemPtr or the one from the first walk (=local walk)
    SyncFileItemPtr item = _syncItemMap.value(key);
    if (!item)
        item = SyncFileItemPtr(new SyncFileItem);

    if (item->_file.isEmpty() || instruction == CSYNC_INSTRUCTION_RENAME) {
        item->_file = fileUtf8;
    }
    item->_originalFile = item->_file;

    if (item->_instruction == CSYNC_INSTRUCTION_NONE
            || (item->_instruction == CSYNC_INSTRUCTION_IGNORE && instruction != CSYNC_INSTRUCTION_NONE)) {
        item->_instruction = instruction;
        item->_modtime = file->modtime;
    } else {
        if (instruction != CSYNC_INSTRUCTION_NONE) {
            qDebug() << "ERROR: Instruction" << item->_instruction << "vs" << instruction << "for" << fileUtf8;
            Q_ASSERT(!"Instructions are both unequal NONE");
            return -1;
        }
    }

    if (file->file_id && strlen(file->file_id) > 0) {
        item->_fileId = file->file_id;
    }
    if (file->directDownloadUrl) {
        item->_directDownloadUrl = QString::fromUtf8( file->directDownloadUrl );
    }
    if (file->directDownloadCookies) {
        item->_directDownloadCookies = QString::fromUtf8( file->directDownloadCookies );
    }
    if (file->remotePerm && file->remotePerm[0]) {
        item->_remotePerm = QByteArray(file->remotePerm);
    }

    item->_should_update_metadata = item->_should_update_metadata || file->should_update_metadata;

    /* The flag "serverHasIgnoredFiles" is true if item in question is a directory
     * that has children which are ignored in sync, either because the files are
     * matched by an ignore pattern, or because they are  hidden.
     *
     * Only the information about the server side ignored files is stored to the
     * database and thus written to the item here. For the local repository its
     * generated by the walk through the real file tree by discovery phase.
     *
     * It needs to go to the sync journal becasue the stat information about remote
     * files are often read from database rather than being pulled from remote.
     */
    if( remote ) {
        item->_serverHasIgnoredFiles    = (file->has_ignored_files > 0);
    }

    // record the seen files to be able to clean the journal later
    _seenFiles.insert(item->_file);
    if (!renameTarget.isEmpty()) {
        // Yes, this record both the rename renameTarget and the original so we keep both in case of a rename
        _seenFiles.insert(renameTarget);
    }

    if (remote && file->remotePerm && file->remotePerm[0]) {
        _remotePerms[item->_file] = file->remotePerm;
    }

    switch(file->error_status) {
    case CSYNC_STATUS_OK:
        break;
    case CSYNC_STATUS_INDIVIDUAL_IS_SYMLINK:
        item->_errorString = tr("Symbolic links are not supported in syncing.");
        break;
    case CSYNC_STATUS_INDIVIDUAL_IGNORE_LIST:
        item->_errorString = tr("File is listed on the ignore list.");
        break;
    case CSYNC_STATUS_INDIVIDUAL_IS_INVALID_CHARS:
        item->_errorString = tr("Filename contains invalid characters that can not be synced cross platform.");
        break;
    case CSYNC_STATUS_INDIVIDUAL_EXCLUDE_LONG_FILENAME:
        item->_errorString = tr("Filename is too long.");
        break;
    case CSYNC_STATUS_INDIVIDUAL_EXCLUDE_HIDDEN:
        item->_errorString = tr("File is ignored because it's hidden.");
        break;
    case CYSNC_STATUS_FILE_LOCKED_OR_OPEN:
        item->_errorString = QLatin1String("File locked"); // don't translate, internal use!
        break;
    case CSYNC_STATUS_INDIVIDUAL_STAT_FAILED:
        item->_errorString = tr("Stat failed.");
        break;
    case CSYNC_STATUS_SERVICE_UNAVAILABLE:
        item->_errorString = QLatin1String("Server temporarily unavailable.");
        break;
    case CSYNC_STATUS_STORAGE_UNAVAILABLE:
        item->_errorString = QLatin1String("Directory temporarily not available on server.");
        item->_status = SyncFileItem::SoftError;
        _temporarilyUnavailablePaths.insert(item->_file);
        break;
    case CSYNC_STATUS_PERMISSION_DENIED:
        item->_errorString = QLatin1String("Directory not accessible on client, permission denied.");
        item->_status = SyncFileItem::SoftError;
        break;
    default:
        Q_ASSERT("Non handled error-status");
        /* No error string */
    }

    if (item->_instruction == CSYNC_INSTRUCTION_IGNORE && (utf8State.invalidChars > 0 || utf8State.remainingChars > 0)) {
        item->_status = SyncFileItem::NormalError;
        //item->_instruction = CSYNC_INSTRUCTION_ERROR;
        item->_errorString = tr("Filename encoding is not valid");
    }

    item->_isDirectory = file->type == CSYNC_FTW_TYPE_DIR;

    // The etag is already set in the previous sync phases somewhere. Maybe we should remove it there
    // and do it here so we have a consistent state about which tree stores information from which source.
    item->_etag = file->etag;
    item->_size = file->size;

    if (!remote) {
        item->_inode = file->inode;
    }

    switch( file->type ) {
    case CSYNC_FTW_TYPE_DIR:
        item->_type = SyncFileItem::Directory;
        break;
    case CSYNC_FTW_TYPE_FILE:
        item->_type = SyncFileItem::File;
        break;
    case CSYNC_FTW_TYPE_SLINK:
        item->_type = SyncFileItem::SoftLink;
        break;
    default:
        item->_type = SyncFileItem::UnknownType;
    }

    SyncFileItem::Direction dir = SyncFileItem::None;

    int re = 0;
    switch(file->instruction) {
    case CSYNC_INSTRUCTION_NONE:
        if (remote && item->_should_update_metadata && !item->_isDirectory && item->_instruction == CSYNC_INSTRUCTION_NONE) {
            // Update the database now already:  New fileid or Etag or RemotePerm
            // Or for files that were detected as "resolved conflict".
            // They should have been a conflict because they both were new, or both
            // had their local mtime or remote etag modified, but the size and mtime
            // is the same on the server.  This typically happen when the database is removed.
            // Nothing will be done for those file, but we still need to update the database.

            // Even if the mtime is different on the server, we always want to keep the mtime from
            // the file system in the DB, this is to avoid spurious upload on the next sync
            item->_modtime = file->other.modtime;

            _journal->setFileRecord(SyncJournalFileRecord(*item, _localPath + item->_file));
            item->_should_update_metadata = false;
        }
        if (item->_isDirectory && file->should_update_metadata) {
            // Because we want still to update etags of directories
            dir = SyncFileItem::None;
        } else {
            // No need to do anything.
            if (file->other.instruction == CSYNC_INSTRUCTION_NONE) {
                _hasNoneFiles = true;
            }

            return re;
        }
        break;
    case CSYNC_INSTRUCTION_RENAME:
        dir = !remote ? SyncFileItem::Down : SyncFileItem::Up;
        item->_renameTarget = renameTarget;
        if (item->_isDirectory)
            _renamedFolders.insert(item->_file, item->_renameTarget);
        break;
    case CSYNC_INSTRUCTION_REMOVE:
        _hasRemoveFile = true;
        dir = !remote ? SyncFileItem::Down : SyncFileItem::Up;
        break;
    case CSYNC_INSTRUCTION_CONFLICT:
    case CSYNC_INSTRUCTION_IGNORE:
    case CSYNC_INSTRUCTION_ERROR:
        dir = SyncFileItem::None;
        break;
    case CSYNC_INSTRUCTION_EVAL:
    case CSYNC_INSTRUCTION_NEW:
    case CSYNC_INSTRUCTION_SYNC:
    case CSYNC_INSTRUCTION_STAT_ERROR:
    default:
        dir = remote ? SyncFileItem::Down : SyncFileItem::Up;
        if (!remote && file->instruction == CSYNC_INSTRUCTION_SYNC) {
            // An upload of an existing file means that the file was left unchanged on the server
            // This count as a NONE for detecting if all the file on the server were changed
            _hasNoneFiles = true;
        }
        break;
    }

    item->_direction = dir;
    if (instruction != CSYNC_INSTRUCTION_NONE) {
        // check for blacklisting of this item.
        // if the item is on blacklist, the instruction was set to ERROR
        checkErrorBlacklisting( *item );
    }

    _progressInfo->adjustTotalsForFile(*item);

    _needsUpdate = true;

    item->log._etag          = file->etag;
    item->log._fileId        = file->file_id;
    item->log._instruction   = file->instruction;
    item->log._modtime       = file->modtime;
    item->log._size          = file->size;

    item->log._other_etag        = file->other.etag;
    item->log._other_fileId      = file->other.file_id;
    item->log._other_instruction = file->other.instruction;
    item->log._other_modtime     = file->other.modtime;
    item->log._other_size        = file->other.size;

    _syncItemMap.insert(key, item);

    emit syncItemDiscovered(*item);
    return re;
}