Esempio n. 1
0
bool VAApiWriter::HWAccellGetImg( const VideoFrame *videoFrame, void *dest, ImgScaler *yv12ToRGB32 ) const
{
	if ( dest && !( outH & 1 ) && !( outW % 4 ) )
	{
		int fmt_count = vaMaxNumImageFormats( VADisp );
		VAImageFormat img_fmt[ fmt_count ];
		if ( vaQueryImageFormats( VADisp, img_fmt, &fmt_count ) == VA_STATUS_SUCCESS )
		{
			const VASurfaceID surfaceID = ( unsigned long )videoFrame->data[ 3 ];
			int img_fmt_idx[ 3 ] = { -1, -1, -1 };
			for ( int i = 0 ; i < fmt_count ; ++i )
			{
				if ( !qstrncmp( ( const char * )&img_fmt[ i ].fourcc, "BGR", 3 ) )
					img_fmt_idx[ 0 ] = i;
				else if ( !qstrncmp( ( const char * )&img_fmt[ i ].fourcc, "YV12", 4 ) )
					img_fmt_idx[ 1 ] = i;
				else if ( !qstrncmp( ( const char * )&img_fmt[ i ].fourcc, "NV12", 4 ) )
					img_fmt_idx[ 2 ] = i;
			}
			return
			(
				( img_fmt_idx[ 0 ] > -1 && getRGB32Image( &img_fmt[ img_fmt_idx[ 0 ] ], surfaceID, dest ) ) ||
				( img_fmt_idx[ 1 ] > -1 && getYV12Image( &img_fmt[ img_fmt_idx[ 1 ] ], surfaceID, dest, yv12ToRGB32 ) ) ||
				( img_fmt_idx[ 2 ] > -1 && getNV12Image( &img_fmt[ img_fmt_idx[ 2 ] ], surfaceID, dest, yv12ToRGB32 ) )
			);
		}
	}
	return false;
}
Esempio n. 2
0
static bool checkQutIMPluginData(const char *data, quint64 *debugId, QString *error)
{
	InfoToken token;
	bool isValidPattern = false;
	bool isValidQutimVersion = false;
	while (scanNextInfoToken(token, data)) {
		if (!qstrncmp("pattern", token.key, token.keyLength)) {
			isValidPattern = !qstrncmp("QUTIM_PLUGIN_VERIFICATION_DATA", token.value, token.valueLength);
			if (!isValidPattern)
				break;
		} else if (!qstrncmp("debugid", token.key, token.keyLength)) {
			if (token.valueLength != 16) {
				*error = QLatin1String("Invalid plugin identification number");
				return false;
			}
			QByteArray data = QByteArray::fromRawData(token.value, token.valueLength);
			QByteArray number = QByteArray::fromHex(data);
			if (number.size() != 8) {
				*error = QLatin1String("Invalid plugin identification number");
				return false;
			}
			*debugId = qFromBigEndian<quint64>(reinterpret_cast<const uchar *>(number.constData()));
		} else if (!qstrncmp("libqutim", token.key, token.keyLength)) {
			isValidQutimVersion = token.valueLength == qstrlen(versionString())
								  && !qstrncmp(versionString(), token.value, token.valueLength);
		}
	}
	if (!isValidPattern)
		*error = QLatin1String("There is no valid qutIM's plugin verification data");
	else if (!isValidQutimVersion)
		*error = QLatin1String("Plugin is built with incompatible libqutim's version");
	return isValidPattern && isValidQutimVersion;
}
Esempio n. 3
0
DataType RDBParser::determineType(char *buf)
{
	QRegExp array_re("(Array \\(\\d+ element\\(s\\)\\))");
	QRegExp hash_re("(Hash \\(\\d+ element\\(s\\)\\))");
	QRegExp string_re("(String \\(length \\d+\\))");
	
	if (qstrncmp(buf, "#<struct", strlen("#<struct")) == 0) {
		return STRUCT_TYPE;
	} else if (qstrncmp(buf, "#<Qt::Color:0x", strlen("#<Qt::Color:0x")) == 0) {
		return COLOR_TYPE;
	} else if (qstrncmp(buf, "#<", strlen("#<")) == 0 && strstr(buf, "=") != 0) {
		// An object instance reference is only expandable and a 'REFERENCE_TYPE'
		// if it contains an '=' (ie it has at least one '@instance_variable=value').
		// Otherwise, treat it as a 'VALUE_TYPE'.
		return REFERENCE_TYPE;
	} else if (array_re.search(buf) != -1) {
		return ARRAY_TYPE;
	} else if (hash_re.search(buf) != -1) {
		return HASH_TYPE;
	} else if (string_re.search(buf) != -1) {
		return STRING_TYPE;
	} else if (qstrncmp(buf, "nil", strlen("nil")) == 0) {
//		return UNKNOWN_TYPE;
		return VALUE_TYPE;
	} else {
		return VALUE_TYPE;
	}
}
bool QAndroidPlatformOpenGLContext::needsFBOReadBackWorkaround()
{
    static bool set = false;
    static bool needsWorkaround = false;

    if (!set) {
        QByteArray env = qgetenv("QT_ANDROID_DISABLE_GLYPH_CACHE_WORKAROUND");
        needsWorkaround = env.isEmpty() || env == "0" || env == "false";

        if (!needsWorkaround) {
            const char *rendererString = reinterpret_cast<const char *>(glGetString(GL_RENDERER));
            needsWorkaround =
                    qstrncmp(rendererString, "Mali-4xx", 6) == 0 // Mali-400, Mali-450
                    || qstrncmp(rendererString, "Adreno (TM) 2xx", 13) == 0 // Adreno 200, 203, 205
                    || qstrncmp(rendererString, "Adreno 2xx", 8) == 0 // Same as above but without the '(TM)'
                    || qstrncmp(rendererString, "Adreno (TM) 30x", 14) == 0 // Adreno 302, 305
                    || qstrncmp(rendererString, "Adreno 30x", 9) == 0 // Same as above but without the '(TM)'
                    || qstrcmp(rendererString, "GC800 core") == 0
                    || qstrcmp(rendererString, "GC1000 core") == 0
                    || qstrcmp(rendererString, "Immersion.16") == 0;
        }

        set = true;
    }

    return needsWorkaround;
}
Esempio n. 5
0
void QQuickOpenGLShaderEffectCommon::lookThroughShaderCode(QQuickItem *item,
                                                           const QMetaObject *itemMetaObject,
                                                           Key::ShaderType shaderType,
                                                           const QByteArray &code)
{
    QQmlPropertyCache *propCache = QQmlData::ensurePropertyCache(qmlEngine(item), item);
    int index = 0;
    int typeIndex = -1;
    int typeLength = 0;
    int nameIndex = -1;
    int nameLength = 0;
    const char *s = code.constData();
    VariableQualifier decl = AttributeQualifier;
    while ((index = qt_search_for_variable(s, code.size(), index, decl, typeIndex, typeLength,
                                           nameIndex, nameLength, shaderType)) != -1)
    {
        if (decl == AttributeQualifier) {
            if (shaderType == Key::VertexShader)
                attributes.append(QByteArray(s + nameIndex, nameLength));
        } else {
            Q_ASSERT(decl == UniformQualifier);

            const int sampLen = sizeof("sampler2D") - 1;
            const int sampExtLen = sizeof("samplerExternalOES") - 1;
            const int opLen = sizeof("qt_Opacity") - 1;
            const int matLen = sizeof("qt_Matrix") - 1;
            const int srLen = sizeof("qt_SubRect_") - 1;

            UniformData d;
            QtPrivate::MappedSlotObject *mapper = nullptr;
            d.name = QByteArray(s + nameIndex, nameLength);
            if (nameLength == opLen && qstrncmp("qt_Opacity", s + nameIndex, opLen) == 0) {
                d.specialType = UniformData::Opacity;
            } else if (nameLength == matLen && qstrncmp("qt_Matrix", s + nameIndex, matLen) == 0) {
                d.specialType = UniformData::Matrix;
            } else if (nameLength > srLen && qstrncmp("qt_SubRect_", s + nameIndex, srLen) == 0) {
                d.specialType = UniformData::SubRect;
            } else {
                if (QQmlPropertyData *pd = propCache->property(QString::fromUtf8(d.name), nullptr, nullptr)) {
                    if (!pd->isFunction())
                        d.propertyIndex = pd->coreIndex();
                }
                const int mappedId = uniformData[shaderType].size() | (shaderType << 16);
                mapper = new QtPrivate::MappedSlotObject([this, mappedId](){
                    this->mappedPropertyChanged(mappedId);
                });
                if (typeLength == sampLen && qstrncmp("sampler2D", s + typeIndex, sampLen) == 0)
                    d.specialType = UniformData::Sampler;
                else if (typeLength == sampExtLen && qstrncmp("samplerExternalOES", s + typeIndex, sampExtLen) == 0)
                    d.specialType = UniformData::SamplerExternal;
                else
                    d.specialType = UniformData::None;
                d.setValueFromProperty(item, itemMetaObject);
            }
            uniformData[shaderType].append(d);
            signalMappers[shaderType].append(mapper);
        }
    }
}
Esempio n. 6
0
void QMetaUtilities::connectSlotsByName(QObject * source, QObject * target)
{
    if (!source || !target) return;

    const QMetaObject * source_mo = source->metaObject();
    const QMetaObject * target_mo = target->metaObject();
    Q_ASSERT(source_mo);
    Q_ASSERT(target_mo);

    // find source's children
    // and add source itself to the list, so we can autoconnect its signals too
    const QObjectList list = source->findChildren<QObject *>(QString()) << source;


    for (int i = 0; i < target_mo->methodCount(); ++i) {
        const char *slot = target_mo->method(i).signature();
        Q_ASSERT(slot);
        if (slot[0] != 'o' || slot[1] != 'n' || slot[2] != '_')
            continue;
        bool foundIt = false;
        for(int j = 0; j < list.count(); ++j) {
            const QObject *co = list.at(j);
            const QMetaObject *smo = co->metaObject();
            QByteArray objName = co->objectName().toAscii();
            int len = objName.length();
            if (!len || qstrncmp(slot + 3, objName.data(), len) || slot[len+3] != '_')
                continue;
            int sigIndex = smo->indexOfSignal(slot + len + 4);
            if (sigIndex < 0) { // search for compatible signals
                int slotlen = qstrlen(slot + len + 4) - 1;
                for (int k = 0; k < co->metaObject()->methodCount(); ++k) {
                    QMetaMethod method = smo->method(k);
                    if (method.methodType() != QMetaMethod::Signal)
                        continue;

                    if (!qstrncmp(method.signature(), slot + len + 4, slotlen)) {
                        sigIndex = k;
                        break;
                    }
                }
            }
            if (sigIndex < 0)
                continue;
            if (QMetaObject::connect(co, sigIndex, target, i)) {
                foundIt = true;
                break;
            }
        }
        if (foundIt) {
            // we found our slot, now skip all overloads
            while (target_mo->method(i + 1).attributes() & QMetaMethod::Cloned)
                  ++i;
        } else if (!(target_mo->method(i).attributes() & QMetaMethod::Cloned)) {
            qWarning("QMetaObject::connectSlotsByName: No matching signal for %s", slot);
        }
    }
}
Esempio n. 7
0
// hacks for broken apps here
// all resource classes are forced to be lowercase
bool Toplevel::resourceMatch(const Toplevel* c1, const Toplevel* c2)
{
    // xv has "xv" as resource name, and different strings starting with "XV" as resource class
    if (qstrncmp(c1->resourceClass(), "xv", 2) == 0 && c1->resourceName() == "xv")
        return qstrncmp(c2->resourceClass(), "xv", 2) == 0 && c2->resourceName() == "xv";
    // Mozilla has "Mozilla" as resource name, and different strings as resource class
    if (c1->resourceName() == "mozilla")
        return c2->resourceName() == "mozilla";
    return c1->resourceClass() == c2->resourceClass();
}
bool VoiceRecorder::onPlay(bool state)
{
	if(isOpened && isPlaying && state)
		return (false);
	if(isRecording)
		return (false);
	if(!state && !isPlaying)
		return (true);
	else if(state && isPlaying)
		return (true);

	if(!state)
	{
		isPlaying = false;
		waveFile.seek(0);
		waveFile.close();

	}
	else
	{
		if(!waveFile.open(QIODevice::ReadOnly))
		{
			isOpened = false;
			isPlaying = false;
			emit statePlay(false);
			qWarning() << "VoiceRecorder : Can't open file for read!";
			return (false);
		}
		waveFile.seek(0);
		if(waveFile.read(reinterpret_cast<char *>(&wavHeader), sizeof(wavHeader)) < 0)
		{
			waveFile.close();
			isOpened = false;
			isPlaying = false;
			emit statePlay(false);
			qWarning() << "VoiceRecorder : file for read is empty!";
			return (false);
		}
		if((qstrncmp(wavHeader.subchunk2ID, "data", 4) != 0) || (qstrncmp(wavHeader.riff, "RIFF", 4) != 0) || (wavHeader.samplesPerSec != samplesPerSec) ||
				  (qstrncmp(wavHeader.wave, "WAVE", 4) != 0) || (qstrncmp(wavHeader.fmt , "fmt ", 4) != 0) || (wavHeader.audioFormat != IEEE_FLOAT))
		{
			waveFile.close();
			isOpened = false;
			isPlaying = false;
			emit statePlay(false);
			qWarning() << "VoiceRecorder : file for read -> bad wave header!";
			return (false);
		}
		playStartPos = waveFile.pos();
		isOpened = true;
		isPlaying = true;
	}
	return (true);
}
Esempio n. 9
0
static bool needsFBOReadBackWorkaround()
{
    static bool set = false;
    static bool needsWorkaround = false;

    if (Q_UNLIKELY(!set)) {
        const char *rendererString = reinterpret_cast<const char *>(glGetString(GL_RENDERER));
        needsWorkaround = qstrncmp(rendererString, "Mali-400", 8) == 0
                          || qstrncmp(rendererString, "Mali-T7", 7) == 0
                          || qstrncmp(rendererString, "PowerVR Rogue G6200", 19) == 0;
        set = true;
    }

    return needsWorkaround;
}
Esempio n. 10
0
error *objectConnect(QObject_ *object, const char *signal, int signalLen, QQmlEngine_ *engine, void *func, int argsLen)
{
    QObject *qobject = reinterpret_cast<QObject *>(object);
    QQmlEngine *qengine = reinterpret_cast<QQmlEngine *>(engine);
    QByteArray qsignal(signal, signalLen);

    const QMetaObject *meta = qobject->metaObject();
    // Walk backwards so descendants have priority.
    for (int i = meta->methodCount()-1; i >= 0; i--) {
            QMetaMethod method = meta->method(i);
            if (method.methodType() == QMetaMethod::Signal) {
                QByteArray name = method.name();
                if (name.length() == signalLen && qstrncmp(name.constData(), signal, signalLen) == 0) {
                    if (method.parameterCount() < argsLen) {
                        // TODO Might continue looking to see if a different signal has the same name and enough arguments.
                        return errorf("signal \"%s\" has too few parameters for provided function", name.constData());
                    }
					Connector *connector = Connector::New(qobject, method, qengine, func, argsLen);
                    const QMetaObject *connmeta = connector->metaObject();
                    QObject::connect(qobject, method, connector, connmeta->method(connmeta->methodOffset()));
                    return 0;
                }
            }
    }
    // Cannot use constData here as the byte array is not null-terminated.
    return errorf("object does not expose a \"%s\" signal", qsignal.data());
}
Esempio n. 11
0
char *qt_parseNsswitchConf(QList<QPrinterDescription> *printers)
{
    QFile nc(QLatin1String("/etc/nsswitch.conf"));
    if (!nc.open(QIODevice::ReadOnly))
        return 0;

    char *defaultPrinter = 0;

    char *line = new char[1025];
    line[1024] = '\0';

    while (!nc.atEnd() &&
            nc.readLine(line, 1024) > 0) {
        if (qstrncmp(line, "printers", 8) == 0) {
            defaultPrinter = qt_parseNsswitchPrintersEntry(printers, line);
            delete[] line;
            return defaultPrinter;
        }
    }

    strcpy(line, "printers: user files nis nisplus xfn");
    defaultPrinter = qt_parseNsswitchPrintersEntry(printers, line);
    delete[] line;
    return defaultPrinter;
}
Esempio n. 12
0
static bool convertMapFile(FTextStream &t,const char *mapName,const QCString relPath,
                           const QCString &context)
{
  QFile f(mapName);
  if (!f.open(IO_ReadOnly))
  {
    err("failed to open map file %s for inclusion in the docs!\n"
        "If you installed Graphviz/dot after a previous failing run, \n"
        "try deleting the output directory and rerun doxygen.\n",mapName);
    return FALSE;
  }
  const int maxLineLen=1024;
  char buf[maxLineLen];
  char url[maxLineLen];
  char ref[maxLineLen];
  int x1,y1,x2,y2;
  while (!f.atEnd())
  {
    bool isRef = FALSE;
    int numBytes = f.readLine(buf,maxLineLen);
    buf[numBytes-1]='\0';
    //printf("ReadLine `%s'\n",buf);
    if (qstrncmp(buf,"rect",4)==0)
    {
      // obtain the url and the coordinates in the order used by graphviz-1.5
      sscanf(buf,"rect %s %d,%d %d,%d",url,&x1,&y1,&x2,&y2);

      if (qstrcmp(url,"\\ref")==0 || qstrcmp(url,"@ref")==0)
      {
        isRef = TRUE;
        sscanf(buf,"rect %s %s %d,%d %d,%d",ref,url,&x1,&y1,&x2,&y2);
      }

      // sanity checks
      if (y2<y1) { int temp=y2; y2=y1; y1=temp; }
      if (x2<x1) { int temp=x2; x2=x1; x1=temp; }

      t << "<area href=\"";

      if ( isRef )
      {
        // handle doxygen \ref tag URL reference
        DocRef *df = new DocRef( (DocNode*) 0, url, context );
        t << externalRef(relPath,df->ref(),TRUE);
        if (!df->file().isEmpty()) t << df->file() << Doxygen::htmlFileExtension;
        if (!df->anchor().isEmpty()) t << "#" << df->anchor();
        delete df;
      }
      else
      {
        t << url;
      }
      t << "\" shape=\"rect\" coords=\""
        << x1 << "," << y1 << "," << x2 << "," << y2 << "\""
        << " alt=\"\"/>" << endl;
    }
  }

  return TRUE;
}
bool QWaveDecoder::findChunk(const char *chunkId)
{
    chunk descriptor;

    do {
        if (!peekChunk(&descriptor))
            return false;

        if (qstrncmp(descriptor.id, chunkId, 4) == 0)
            return true;

        // It's possible that bytes->available() is less than the chunk size
        // if it's corrupt.
        junkToSkip = qint64(sizeof(chunk) + descriptor.size);

        // Skip the current amount
        if (junkToSkip > 0)
            discardBytes(junkToSkip);

        // If we still have stuff left, just exit and try again later
        // since we can't call peekChunk
        if (junkToSkip > 0)
            return false;

    } while (source->bytesAvailable() > 0);

    return false;
}
Esempio n. 14
0
static long qt_find_pattern(const char *s, ulong s_len,
                             const char *pattern, ulong p_len)
{
    /*
      we search from the end of the file because on the supported
      systems, the read-only data/text segments are placed at the end
      of the file.  HOWEVER, when building with debugging enabled, all
      the debug symbols are placed AFTER the data/text segments.

      what does this mean?  when building in release mode, the search
      is fast because the data we are looking for is at the end of the
      file... when building in debug mode, the search is slower
      because we have to skip over all the debugging symbols first
    */

    if (! s || ! pattern || p_len > s_len) return -1;
    ulong i, hs = 0, hp = 0, delta = s_len - p_len;

    for (i = 0; i < p_len; ++i) {
        hs += s[delta + i];
        hp += pattern[i];
    }
    i = delta;
    for (;;) {
        if (hs == hp && qstrncmp(s + i, pattern, p_len) == 0)
            return i;
        if (i == 0)
            break;
        --i;
        hs -= s[i + p_len];
        hs += s[i];
    }

    return -1;
}
Esempio n. 15
0
static void continueInWindow(QString _wname)
{
    QCString wname = _wname.latin1();
    int id = -1;

    KStringList apps = kapp->dcopClient()->registeredApplications();
    for(KStringList::Iterator it = apps.begin(); it != apps.end(); ++it)
    {
        QCString &clientId = *it;

        if(qstrncmp(clientId, wname, wname.length()) != 0)
            continue;

        DCOPRef client(clientId.data(), wname + "-mainwindow#1");
        DCOPReply result = client.call("getWinID()");

        if(result.isValid())
        {
            id = (int)result;
            break;
        }
    }

    KWin::activateWindow(id);
}
Esempio n. 16
0
// Compare by char sequences, then by their position in main sequence
int SArrayIndex::compare(const char* seq1, const char* seq2) const {
    //TODO: use memcmp instead?
    int res = qstrncmp(seq1, seq2, w);
    return res; //==0 ? seq1-seq2 : res;

//     const quint32* a1 = (const quint32*)seq1;
//     const quint32* a2 = (const quint32*)seq2;
//     int rc = 0;
//     for (const quint32* aend1 = a1 + w4; a1 < aend1; a1++, a2++) {
//         rc = *a1-*a2;
//         if (rc != 0) {
//             return rc;
//         }
//     }
//     if (wRest > 0) {
//         const char* b1 = (const char*)a1;
//         const char* b2 = (const char*)a2;
//         rc = *b1 - *b2;
//         if (rc!=0) {
//             return rc;
//         }
//         if (wRest > 1) {
//             b1++; b2++;
//             rc = *b1-*b2;
//             if (rc != 0) {
//                 return rc;
//             }
//             return wRest > 2 ? *++b1-*++b2: 0;
//         }
//     }
//     return seq1-seq2;
}
WidgetInformation::WidgetInformation( const QString& filePath, const WidgetContextType& op )
    : m_ContentType( EContentInvalid ),
      m_ContextType( op )
{
    // Set the property filePath
    m_Properties[ EPropertyFilePath ] = filePath;
    
    if( QFileInfo( filePath ).isDir() )
    {
        //TODO: Need to check the required feature.
        // if required we need to implement SuperWidget::getWidgetType(const QString& path)
    }
    else if ( filePath.endsWith( WidgetExtensionWGT, Qt::CaseInsensitive ) )
    {
        QFile file( filePath );
        file.open( QIODevice::ReadOnly );

        if ( 0 == qstrncmp( WidgetPackageMagicNumber, file.read(4).data(), 4 ) )
            m_ContentType = EContentWgt;
        
        file.close();
    }
    else
    {
        m_ContentType = EContentInvalid;
    }
}
int SCString::findRev( const char *str, int index, bool cs) const
{
  int slen = qstrlen(str);
  uint len = length();
  if ( index < 0 )                           // neg index ==> start from end
    index = len-slen;
  else if ( (uint)index > len )              // bad index
    return -1;
  else if ( (uint)(index + slen) > len )     // str would be too long
    index = len - slen;
  if ( index < 0 )
    return -1;

  register char *d = m_data + index;
  if ( cs )                     // case sensitive 
  {      
    for ( int i=index; i>=0; i-- )
      if ( qstrncmp(d--,str,slen)==0 )
        return i;
  } 
  else                          // case insensitive
  {           
    for ( int i=index; i>=0; i-- )
      if ( qstrnicmp(d--,str,slen)==0 )
        return i;
  }
  return -1;

}
Esempio n. 19
0
void portable_unsetenv(const char *variable)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
    SetEnvironmentVariable(variable,0);
#else
    /* Some systems don't have unsetenv(), so we do it ourselves */
    size_t len;
    char **ep;

    if (variable == NULL || *variable == '\0' || strchr (variable, '=') != NULL)
    {
      return; // not properly formatted
    }

    len = qstrlen(variable);

    ep = environ;
    while (*ep != NULL)
    {
      if (!qstrncmp(*ep, variable, (uint)len) && (*ep)[len]=='=')
      {
        /* Found it.  Remove this pointer by moving later ones back.  */
        char **dp = ep;
        do dp[0] = dp[1]; while (*dp++);
        /* Continue the loop in case NAME appears again.  */
      }
      else
      {
        ++ep;
      }
    }
#endif
}
Esempio n. 20
0
/*!
    Construct a new QTgaFile object getting data from \a device.

    The object does not take ownership of the \a device, but until the
    object is destroyed do not do any non-const operations, eg seek or
    read on the device.
*/
QTgaFile::QTgaFile(QIODevice *device)
    : mDevice(device)
{
    ::memset(mHeader, 0, HeaderSize);
    if (!mDevice->isReadable())
    {
        mErrorMessage = tr("Could not read image data");
        return;
    }
    if (mDevice->isSequential())
    {
        mErrorMessage = tr("Sequential device (eg socket) for image read not supported");
        return;
    }
    if (!mDevice->seek(0))
    {
        mErrorMessage = tr("Seek file/device for image read failed");
        return;
    }
    int bytes = device->read((char*)mHeader, HeaderSize);
    if (bytes != HeaderSize)
    {
        mErrorMessage = tr("Image header read failed");
        return;
    }
    if (mHeader[ImageType] != 2)
    {
        // TODO: should support other image types
        mErrorMessage = tr("Image type not supported");
        return;
    }
    int bitsPerPixel = mHeader[PixelDepth];
    bool validDepth = (bitsPerPixel == 16 || bitsPerPixel == 24 || bitsPerPixel == 32);
    if (!validDepth)
    {
        mErrorMessage = tr("Image depth not valid");
    }
    int curPos = mDevice->pos();
    int fileBytes = mDevice->size();
    if (!mDevice->seek(fileBytes - FooterSize))
    {
        mErrorMessage = tr("Could not seek to image read footer");
        return;
    }
    char footer[FooterSize];
    bytes = mDevice->read((char*)footer, FooterSize);
    if (bytes != FooterSize)
    {
        mErrorMessage = tr("Could not read footer");
    }
    if (qstrncmp(&footer[SignatureOffset], "TRUEVISION-XFILE", 16) != 0)
    {
        mErrorMessage = tr("Image type (non-TrueVision 2.0) not supported");
    }
    if (!mDevice->seek(curPos))
    {
        mErrorMessage = tr("Could not reset to read data");
    }
}
Esempio n. 21
0
void Model::DjVuDocument::loadProperties(QStandardItemModel* propertiesModel) const
{
    Document::loadProperties(propertiesModel);

    QMutexLocker mutexLocker(&m_mutex);

    propertiesModel->setColumnCount(2);

    miniexp_t annoExp;

    while(true)
    {
        annoExp = ddjvu_document_get_anno(m_document, TRUE);

        if(annoExp == miniexp_dummy)
        {
            clearMessageQueue(m_context, true);
        }
        else
        {
            break;
        }
    }

    const int annoLength = miniexp_length(annoExp);

    for(int annoN = 0; annoN < annoLength; ++annoN)
    {
        miniexp_t listExp = miniexp_nth(annoN, annoExp);
        const int listLength = miniexp_length(listExp);

        if(listLength <= 1 || qstrncmp(miniexp_to_name(miniexp_nth(0, listExp)), "metadata", 8) != 0)
        {
            continue;
        }

        for(int listN = 1; listN < listLength; ++listN)
        {
            miniexp_t keyValueExp = miniexp_nth(listN, listExp);

            if(miniexp_length(keyValueExp) != 2)
            {
                continue;
            }

            const QString key = QString::fromUtf8(miniexp_to_name(miniexp_nth(0, keyValueExp)));
            const QString value = QString::fromUtf8(miniexp_to_str(miniexp_nth(1, keyValueExp)));

            if(!key.isEmpty() && !value.isEmpty())
            {
                propertiesModel->appendRow(QList< QStandardItem* >() << new QStandardItem(key) << new QStandardItem(value));
            }
        }
    }

    ddjvu_miniexp_release(m_document, annoExp);
}
Esempio n. 22
0
void CryptoDocPrivate::cleanProperties()
{
	for( int i = enc->encProperties.nEncryptionProperties - 1; i >= 0; --i )
	{
		DEncEncryptionProperty *p = enc->encProperties.arrEncryptionProperties[i];
		if( qstrncmp( p->szName, "orig_file", 9 ) == 0 )
			dencEncryptedData_DeleteEncryptionProperty( enc, i );
	}
}
bool QWaveDecoder::enoughDataAvailable()
{
    chunk descriptor;
    if (!peekChunk(&descriptor, false))
        return false;

    // This is only called for the RIFF/RIFX header, before bigEndian is set,
    // so we have to manually swizzle
    if (qstrncmp(descriptor.id, "RIFX", 4) == 0)
        descriptor.size = qFromBigEndian<quint32>(descriptor.size);
    if (qstrncmp(descriptor.id, "RIFF", 4) == 0)
        descriptor.size = qFromLittleEndian<quint32>(descriptor.size);

    if (source->bytesAvailable() < qint64(sizeof(chunk) + descriptor.size))
        return false;

    return true;
}
Esempio n. 24
0
void WaveDecoder::handleData()
{
    if (source->bytesAvailable() < qint64(sizeof(CombinedHeader) + sizeof(DATAHeader) + sizeof(quint16)))
        return;

    source->disconnect(SIGNAL(readyRead()), this, SLOT(handleData()));
    source->read((char*)&header, sizeof(CombinedHeader));

    if (qstrncmp(header.riff.descriptor.id, "RIFF", 4) != 0 ||
        qstrncmp(header.riff.type, "WAVE", 4) != 0 ||
        qstrncmp(header.wave.descriptor.id, "fmt ", 4) != 0 ||
        (header.wave.audioFormat != 0 && header.wave.audioFormat != 1)) {

        emit invalidFormat();
    }
    else {
        DATAHeader dataHeader;

        if (qFromLittleEndian<quint32>(header.wave.descriptor.size) > sizeof(WAVEHeader)) {
            // Extended data available
            quint16 extraFormatBytes;
            source->peek((char*)&extraFormatBytes, sizeof(quint16));
            extraFormatBytes = qFromLittleEndian<quint16>(extraFormatBytes);
            source->read(sizeof(quint16) + extraFormatBytes);   // dump it all
        }

        source->read((char*)&dataHeader, sizeof(DATAHeader));

        int bps = qFromLittleEndian<quint16>(header.wave.bitsPerSample);

        format.setCodec(QLatin1String("audio/pcm"));
        format.setSampleType(bps == 8 ? QAudioFormat::UnSignedInt : QAudioFormat::SignedInt);
        format.setByteOrder(QAudioFormat::LittleEndian);
        format.setFrequency(qFromLittleEndian<quint32>(header.wave.sampleRate));
        format.setSampleSize(bps);
        format.setChannels(qFromLittleEndian<quint16>(header.wave.numChannels));

        dataSize = qFromLittleEndian<quint32>(dataHeader.descriptor.size);

        haveFormat = true;
        connect(source, SIGNAL(readyRead()), SIGNAL(readyRead()));
        emit formatKnown();
    }
}
void QQuickShaderEffectCommon::lookThroughShaderCode(QQuickItem *item, Key::ShaderType shaderType, const QByteArray &code)
{
    int index = 0;
    int typeIndex = -1;
    int typeLength = 0;
    int nameIndex = -1;
    int nameLength = 0;
    const char *s = code.constData();
    VariableQualifier decl = AttributeQualifier;
    while ((index = qt_search_for_variable(s, code.size(), index, decl, typeIndex, typeLength,
                                           nameIndex, nameLength, shaderType)) != -1)
    {
        if (decl == AttributeQualifier) {
            if (shaderType == Key::VertexShader)
                attributes.append(QByteArray(s + nameIndex, nameLength));
        } else {
            Q_ASSERT(decl == UniformQualifier);

            const int sampLen = sizeof("sampler2D") - 1;
            const int opLen = sizeof("qt_Opacity") - 1;
            const int matLen = sizeof("qt_Matrix") - 1;
            const int srLen = sizeof("qt_SubRect_") - 1;

            UniformData d;
            QSignalMapper *mapper = 0;
            d.name = QByteArray(s + nameIndex, nameLength);
            if (nameLength == opLen && qstrncmp("qt_Opacity", s + nameIndex, opLen) == 0) {
                d.specialType = UniformData::Opacity;
            } else if (nameLength == matLen && qstrncmp("qt_Matrix", s + nameIndex, matLen) == 0) {
                d.specialType = UniformData::Matrix;
            } else if (nameLength > srLen && qstrncmp("qt_SubRect_", s + nameIndex, srLen) == 0) {
                d.specialType = UniformData::SubRect;
            } else {
                mapper = new QSignalMapper;
                mapper->setMapping(item, uniformData[shaderType].size() | (shaderType << 16));
                d.value = item->property(d.name.constData());
                bool sampler = typeLength == sampLen && qstrncmp("sampler2D", s + typeIndex, sampLen) == 0;
                d.specialType = sampler ? UniformData::Sampler : UniformData::None;
            }
            uniformData[shaderType].append(d);
            signalMappers[shaderType].append(mapper);
        }
    }
}
Esempio n. 26
0
QString FileItem::getMimeType()
{
    if (mimeType.isEmpty()) {
        getContent();

        const char *contentData = content.constData();
        if (content.size() < 10)
            mimeType = "application/octet-stream";
        else if (qstrncmp("GIF", contentData, 3))
            mimeType = "image/gif";
        else if (qstrncmp("PNG", contentData + 1, 3))
            mimeType = "image/png";
        else if (qstrncmp("JFIF", contentData + 6, 4))
            mimeType = "image/jpeg";
        else if (qstrncmp("BM", contentData, 2))
            mimeType = "image/bmp";
    }
    return mimeType;
}
Esempio n. 27
0
QT_BEGIN_NAMESPACE

#ifdef Q_OS_WIN
static inline bool isAxWidget(const QObject *o)
{
    // Is it one of  QDesignerAxWidget/QDesignerAxPluginWidget?
    static const char *axWidgetName = "QDesignerAx";
    static const unsigned axWidgetNameLen = qstrlen(axWidgetName);
    return qstrncmp(o->metaObject()->className(), axWidgetName, axWidgetNameLen) == 0;
}
Esempio n. 28
0
bool QCString::stripPrefix(const char *prefix)
{
  if (prefix==0 || length()==0) return FALSE;
  int len = qstrlen(prefix);
  if (qstrncmp(prefix,data(),len)==0)
  {
    m_rep=mid(len,length()-len).m_rep; // need to make a deep copy
    return TRUE;
  }
  return FALSE;
}
Esempio n. 29
0
/*
  returns true if the string s was correctly parsed, false otherwise.
*/
static bool qt_parse_pattern(const char *s, uint *version, bool *debug, QByteArray *key)
{
    bool ret = true;

    qt_token_info pinfo("=\n", 2);
    int parse;
    ulong at = 0, advance, parselen = qstrlen(s);
    do {
        parse = qt_tokenize(s + at, parselen, &advance, pinfo);
        if (parse == -1) {
            ret = false;
            break;
        }

        at += advance;
        parselen -= advance;

        if (qstrncmp("version", pinfo.results[0], pinfo.lengths[0]) == 0) {
            // parse version string
            qt_token_info pinfo2("..-", 3);
            if (qt_tokenize(pinfo.results[1], pinfo.lengths[1],
                              &advance, pinfo2) != -1) {
                QByteArray m(pinfo2.results[0], pinfo2.lengths[0]);
                QByteArray n(pinfo2.results[1], pinfo2.lengths[1]);
                QByteArray p(pinfo2.results[2], pinfo2.lengths[2]);
                *version  = (m.toUInt() << 16) | (n.toUInt() << 8) | p.toUInt();
            } else {
                ret = false;
                break;
            }
        } else if (qstrncmp("debug", pinfo.results[0], pinfo.lengths[0]) == 0) {
            *debug = qstrncmp("true", pinfo.results[1], pinfo.lengths[1]) == 0;
        } else if (qstrncmp("buildkey", pinfo.results[0],
                              pinfo.lengths[0]) == 0){
            // save buildkey
            *key = QByteArray(pinfo.results[1], pinfo.lengths[1]);
        }
    } while (parse == 1 && parselen > 0);

    return ret;
}
Esempio n. 30
0
static void designerMessageHandler(QtMsgType type, const char *msg)
{
    // Only Designer warnings are displayed as box
    QDesigner *designerApp = qDesigner;
    if (type != QtWarningMsg || !designerApp || qstrncmp(designerWarningPrefix, msg, qstrlen(designerWarningPrefix))) {
        qInstallMsgHandler(0);
        qt_message_output(type, msg);
        qInstallMsgHandler (designerMessageHandler);
        return;
    }
    designerApp->showErrorMessage(msg);
}