当前位置: 首页>>代码示例>>C++>>正文


C++ QScopedPointer::data方法代码示例

本文整理汇总了C++中QScopedPointer::data方法的典型用法代码示例。如果您正苦于以下问题:C++ QScopedPointer::data方法的具体用法?C++ QScopedPointer::data怎么用?C++ QScopedPointer::data使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QScopedPointer的用法示例。


在下文中一共展示了QScopedPointer::data方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: hash

void KeePass2Writer::writeDatabase(QIODevice* device, Database* db)
{
    m_error = false;
    m_errorStr.clear();

    QByteArray masterSeed = randomGen()->randomArray(32);
    QByteArray encryptionIV = randomGen()->randomArray(16);
    QByteArray protectedStreamKey = randomGen()->randomArray(32);
    QByteArray startBytes = randomGen()->randomArray(32);
    QByteArray endOfHeader = "\r\n\r\n";

    CryptoHash hash(CryptoHash::Sha256);
    hash.addData(masterSeed);
    Q_ASSERT(!db->transformedMasterKey().isEmpty());
    hash.addData(db->transformedMasterKey());
    QByteArray finalKey = hash.result();

    QBuffer header;
    header.open(QIODevice::WriteOnly);
    m_device = &header;

    CHECK_RETURN(writeData(Endian::int32ToBytes(KeePass2::SIGNATURE_1, KeePass2::BYTEORDER)));
    CHECK_RETURN(writeData(Endian::int32ToBytes(KeePass2::SIGNATURE_2, KeePass2::BYTEORDER)));
    CHECK_RETURN(writeData(Endian::int32ToBytes(KeePass2::FILE_VERSION, KeePass2::BYTEORDER)));

    CHECK_RETURN(writeHeaderField(KeePass2::CipherID, db->cipher().toByteArray()));
    CHECK_RETURN(writeHeaderField(KeePass2::CompressionFlags,
                                  Endian::int32ToBytes(db->compressionAlgo(),
                                                       KeePass2::BYTEORDER)));
    CHECK_RETURN(writeHeaderField(KeePass2::MasterSeed, masterSeed));
    CHECK_RETURN(writeHeaderField(KeePass2::TransformSeed, db->transformSeed()));
    CHECK_RETURN(writeHeaderField(KeePass2::TransformRounds,
                                  Endian::int64ToBytes(db->transformRounds(),
                                                       KeePass2::BYTEORDER)));
    CHECK_RETURN(writeHeaderField(KeePass2::EncryptionIV, encryptionIV));
    CHECK_RETURN(writeHeaderField(KeePass2::ProtectedStreamKey, protectedStreamKey));
    CHECK_RETURN(writeHeaderField(KeePass2::StreamStartBytes, startBytes));
    CHECK_RETURN(writeHeaderField(KeePass2::InnerRandomStreamID,
                                  Endian::int32ToBytes(KeePass2::Salsa20,
                                                       KeePass2::BYTEORDER)));
    CHECK_RETURN(writeHeaderField(KeePass2::EndOfHeader, endOfHeader));

    header.close();
    m_device = device;
    QByteArray headerHash = CryptoHash::hash(header.data(), CryptoHash::Sha256);
    CHECK_RETURN(writeData(header.data()));

    SymmetricCipherStream cipherStream(device, SymmetricCipher::Aes256, SymmetricCipher::Cbc,
                                       SymmetricCipher::Encrypt, finalKey, encryptionIV);
    cipherStream.open(QIODevice::WriteOnly);
    m_device = &cipherStream;
    CHECK_RETURN(writeData(startBytes));

    HashedBlockStream hashedStream(&cipherStream);
    hashedStream.open(QIODevice::WriteOnly);

    QScopedPointer<QtIOCompressor> ioCompressor;

    if (db->compressionAlgo() == Database::CompressionNone) {
        m_device = &hashedStream;
    }
    else {
        ioCompressor.reset(new QtIOCompressor(&hashedStream));
        ioCompressor->setStreamFormat(QtIOCompressor::GzipFormat);
        ioCompressor->open(QIODevice::WriteOnly);
        m_device = ioCompressor.data();
    }

    KeePass2RandomStream randomStream(protectedStreamKey);

    KeePass2XmlWriter xmlWriter;
    xmlWriter.writeDatabase(m_device, db, &randomStream, headerHash);
}
开发者ID:AlbertWeichselbraun,项目名称:keepassx,代码行数:73,代码来源:KeePass2Writer.cpp

示例2: main

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString serialPortName;
    QString serialPortFriendlyName;
    QString sisFile;
    QString exeFile;
    QStringList cmdLine;
    QStringList args = QCoreApplication::arguments();
    QTextStream outstream(stdout);
    QTextStream errstream(stderr);
    QString uploadLocalFile;
    QString uploadRemoteFile;
    QString downloadRemoteFile;
    QString downloadLocalFile;
    QString dstName = "c:\\data\\testtemp.sis";
    int loglevel=1;
    int timeout=0;
    bool crashlog = true;
    enum {AgentUnknown, AgentCoda, AgentTRK} debugAgent = AgentUnknown;
    QString crashlogpath;
    QListIterator<QString> it(args);
    it.next(); //skip name of program
    while (it.hasNext()) {
        QString arg = it.next();

        if (arg.startsWith("-")) {
            if (arg == "--portname" || arg == "-p") {
                CHECK_PARAMETER_EXISTS
                serialPortName = it.next();
            }
            else if (arg == "--portfriendlyname" || arg == "-f") {
                CHECK_PARAMETER_EXISTS
                serialPortFriendlyName = it.next();
            }
            else if (arg == "--sis" || arg == "-s") {
                CHECK_PARAMETER_EXISTS
                sisFile = it.next();
                if (!QFileInfo(sisFile).exists()) {
                    errstream << "Sis file (" << sisFile << ") doesn't exist" << endl;
                    return 1;
                }
            }
            else if (arg == "--upload" || arg == "-u") {
                CHECK_PARAMETER_EXISTS
                uploadLocalFile = it.next();
                if (!QFileInfo(uploadLocalFile).exists()) {
                    errstream << "Executable file (" << uploadLocalFile << ") doesn't exist" << endl;
                    return 1;
                }
                CHECK_PARAMETER_EXISTS
                uploadRemoteFile = it.next();
            }
            else if (arg == "--download" || arg == "-d") {
                CHECK_PARAMETER_EXISTS
                downloadRemoteFile = it.next();
                CHECK_PARAMETER_EXISTS
                downloadLocalFile = it.next();
                QFileInfo downloadInfo(downloadLocalFile);
                if (downloadInfo.exists() && !downloadInfo.isFile()) {
                    errstream << downloadLocalFile << " is not a file." << endl;
                    return 1;
                }
            }
            else if (arg == "--timeout" || arg == "-t") {
                CHECK_PARAMETER_EXISTS
                bool ok;
                timeout = it.next().toInt(&ok);
                if (!ok) {
                    errstream << "Timeout must be specified in milliseconds" << endl;
                    return 1;
                }
            }
            else if (arg == "--coda")
                debugAgent = AgentCoda;
            else if (arg == "--trk")
                debugAgent = AgentTRK;
            else if (arg == "--tempfile" || arg == "-T") {
                CHECK_PARAMETER_EXISTS
                dstName = it.next();
            }
            else if (arg == "--verbose" || arg == "-v")
                loglevel=2;
            else if (arg == "--quiet" || arg == "-q")
                loglevel=0;
            else if (arg == "--nocrashlog")
                crashlog = false;
            else if (arg == "--crashlogpath") {
                CHECK_PARAMETER_EXISTS
                crashlogpath = it.next();
            }
            else
                errstream << "unknown command line option " << arg << endl;
        } else {
            exeFile = arg;
            while(it.hasNext()) {
                cmdLine.append(it.next());
            }
        }
//.........这里部分代码省略.........
开发者ID:AtlantisCD9,项目名称:Qt,代码行数:101,代码来源:main.cpp

示例3: initPrimerUdr

void PrimerLibrary::initPrimerUdr(U2OpStatus &os) {
    CHECK(NULL == AppContext::getUdrSchemaRegistry()->getSchemaById(PRIMER_UDR_ID), );

    UdrSchema::FieldDesc name("name", UdrSchema::STRING);
    UdrSchema::FieldDesc sequence("sequence", UdrSchema::STRING);
    UdrSchema::FieldDesc gc("GC", UdrSchema::DOUBLE);
    UdrSchema::FieldDesc tm("Tm", UdrSchema::DOUBLE);

    QScopedPointer<UdrSchema> primerSchema(new UdrSchema(PRIMER_UDR_ID));
    primerSchema->addField(name, os);
    primerSchema->addField(sequence, os);
    primerSchema->addField(gc, os);
    primerSchema->addField(tm, os);
    CHECK_OP(os, );

    AppContext::getUdrSchemaRegistry()->registerSchema(primerSchema.data(), os);
    if (!os.hasError()) {
        primerSchema.take();
    }
}

void PrimerLibrary::addPrimer(const Primer &primer, U2OpStatus &os) {
    QList<UdrValue> values;
    values << UdrValue(primer.name);
    values << UdrValue(primer.sequence);
    values << UdrValue(primer.gc);
    values << UdrValue(primer.tm);
    UdrRecordId record = udrDbi->addRecord(PRIMER_UDR_ID, values, os);
    CHECK_OP(os, );

    emit si_primerAdded(record.getRecordId());
开发者ID:ugeneunipro,项目名称:ugene-old,代码行数:31,代码来源:PrimerLibrary.cpp

示例4: self

TankInfoModel *TankInfoModel::instance()
{
	static QScopedPointer<TankInfoModel> self(new TankInfoModel());
	return self.data();
}
开发者ID:ryanlerch,项目名称:subsurface,代码行数:5,代码来源:models.cpp

示例5: item

void QgsVectorLayerRenderer::drawRendererV2Levels( QgsFeatureIterator& fit )
{
  QHash< QgsSymbolV2*, QList<QgsFeature> > features; // key = symbol, value = array of features

  QgsSingleSymbolRendererV2* selRenderer = nullptr;
  if ( !mSelectedFeatureIds.isEmpty() )
  {
    selRenderer = new QgsSingleSymbolRendererV2( QgsSymbolV2::defaultSymbol( mGeometryType ) );
    selRenderer->symbol()->setColor( mContext.selectionColor() );
    selRenderer->setVertexMarkerAppearance( mVertexMarkerStyle, mVertexMarkerSize );
    selRenderer->startRender( mContext, mFields );
  }

  QgsExpressionContextScope* symbolScope = QgsExpressionContextUtils::updateSymbolScope( nullptr, new QgsExpressionContextScope() );
  mContext.expressionContext().appendScope( symbolScope );

  // 1. fetch features
  QgsFeature fet;
  while ( fit.nextFeature( fet ) )
  {
    if ( mContext.renderingStopped() )
    {
      qDebug( "rendering stop!" );
      stopRendererV2( selRenderer );
      delete mContext.expressionContext().popScope();
      return;
    }

    if ( !fet.constGeometry() )
      continue; // skip features without geometry

    mContext.expressionContext().setFeature( fet );
    QgsSymbolV2* sym = mRendererV2->symbolForFeature( fet, mContext );
    if ( !sym )
    {
      continue;
    }

    if ( !features.contains( sym ) )
    {
      features.insert( sym, QList<QgsFeature>() );
    }
    features[sym].append( fet );

    if ( mCache )
    {
      // Cache this for the use of (e.g.) modifying the feature's uncommitted geometry.
      mCache->cacheGeometry( fet.id(), *fet.constGeometry() );
    }

    if ( mContext.labelingEngine() )
    {
      mContext.expressionContext().setFeature( fet );
      if ( mLabeling )
      {
        mContext.labelingEngine()->registerFeature( mLayerID, fet, mContext );
      }
      if ( mDiagrams )
      {
        mContext.labelingEngine()->registerDiagramFeature( mLayerID, fet, mContext );
      }
    }
    // new labeling engine
    if ( mContext.labelingEngineV2() )
    {
      QScopedPointer<QgsGeometry> obstacleGeometry;
      QgsSymbolV2List symbols = mRendererV2->originalSymbolsForFeature( fet, mContext );

      if ( !symbols.isEmpty() && fet.constGeometry()->type() == QGis::Point )
      {
        obstacleGeometry.reset( QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, mContext, symbols ) );
      }

      if ( !symbols.isEmpty() )
      {
        QgsExpressionContextUtils::updateSymbolScope( symbols.at( 0 ), symbolScope );
      }

      if ( mLabelProvider )
      {
        mLabelProvider->registerFeature( fet, mContext, obstacleGeometry.data() );
      }
      if ( mDiagramProvider )
      {
        mDiagramProvider->registerFeature( fet, mContext, obstacleGeometry.data() );
      }
    }
  }

  delete mContext.expressionContext().popScope();

  // find out the order
  QgsSymbolV2LevelOrder levels;
  QgsSymbolV2List symbols = mRendererV2->symbols( mContext );
  for ( int i = 0; i < symbols.count(); i++ )
  {
    QgsSymbolV2* sym = symbols[i];
    for ( int j = 0; j < sym->symbolLayerCount(); j++ )
    {
      int level = sym->symbolLayer( j )->renderingPass();
//.........这里部分代码省略.........
开发者ID:Clayton-Davis,项目名称:QGIS,代码行数:101,代码来源:qgsvectorlayerrenderer.cpp

示例6: renderScene

/******************************************************************************
* This is the high-level rendering function, which invokes the renderer to generate one or more
* output images of the scene. All rendering parameters are specified in the RenderSettings object.
******************************************************************************/
bool DataSet::renderScene(RenderSettings* settings, Viewport* viewport, QSharedPointer<FrameBuffer> frameBuffer, FrameBufferWindow* frameBufferWindow)
{
    OVITO_CHECK_OBJECT_POINTER(settings);
    OVITO_CHECK_OBJECT_POINTER(viewport);

    // If the caller did not supply a frame buffer, get the default frame buffer for the output image, or create a temporary one if necessary.
    if(!frameBuffer) {
        if(Application::instance().guiMode()) {
            OVITO_ASSERT(mainWindow());
            frameBufferWindow = mainWindow()->frameBufferWindow();
            frameBuffer = frameBufferWindow->frameBuffer();
        }
        if(!frameBuffer) {
            frameBuffer.reset(new FrameBuffer(settings->outputImageWidth(), settings->outputImageHeight()));
        }
    }

    // Get the selected scene renderer.
    SceneRenderer* renderer = settings->renderer();
    if(!renderer) throw Exception(tr("No renderer has been selected."));

    bool wasCanceled = false;
    try {

        // Set up the frame buffer for the output image.
        if(frameBufferWindow && frameBufferWindow->frameBuffer() != frameBuffer) {
            frameBufferWindow->setFrameBuffer(frameBuffer);
            frameBufferWindow->resize(frameBufferWindow->sizeHint());
        }
        if(frameBuffer->size() != QSize(settings->outputImageWidth(), settings->outputImageHeight())) {
            frameBuffer->setSize(QSize(settings->outputImageWidth(), settings->outputImageHeight()));
            frameBuffer->clear();
            if(frameBufferWindow)
                frameBufferWindow->resize(frameBufferWindow->sizeHint());
        }
        if(frameBufferWindow) {
            if(frameBufferWindow->isHidden()) {
                // Center frame buffer window in main window.
                if(frameBufferWindow->parentWidget()) {
                    QSize s = frameBufferWindow->frameGeometry().size();
                    frameBufferWindow->move(frameBufferWindow->parentWidget()->geometry().center() - QPoint(s.width() / 2, s.height() / 2));
                }
                frameBufferWindow->show();
            }
            frameBufferWindow->activateWindow();
        }

        // Show progress dialog.
        std::unique_ptr<QProgressDialog> progressDialog;
        if(Application::instance().guiMode()) {
            progressDialog.reset(new QProgressDialog(frameBufferWindow ? (QWidget*)frameBufferWindow : (QWidget*)mainWindow()));
            progressDialog->setWindowModality(Qt::WindowModal);
            progressDialog->setAutoClose(false);
            progressDialog->setAutoReset(false);
            progressDialog->setMinimumDuration(0);
            progressDialog->setValue(0);
        }

        // Don't update viewports while rendering.
        ViewportSuspender noVPUpdates(this);

        // Initialize the renderer.
        if(renderer->startRender(this, settings)) {

            VideoEncoder* videoEncoder = nullptr;
#ifdef OVITO_VIDEO_OUTPUT_SUPPORT
            QScopedPointer<VideoEncoder> videoEncoderPtr;
            // Initialize video encoder.
            if(settings->saveToFile() && settings->imageInfo().isMovie()) {

                if(settings->imageFilename().isEmpty())
                    throw Exception(tr("Cannot save rendered images to movie file. Output filename has not been specified."));

                videoEncoderPtr.reset(new VideoEncoder());
                videoEncoder = videoEncoderPtr.data();
                videoEncoder->openFile(settings->imageFilename(), settings->outputImageWidth(), settings->outputImageHeight(), animationSettings()->framesPerSecond());
            }
#endif

            if(settings->renderingRangeType() == RenderSettings::CURRENT_FRAME) {
                // Render a single frame.
                TimePoint renderTime = animationSettings()->time();
                int frameNumber = animationSettings()->timeToFrame(renderTime);
                if(frameBufferWindow)
                    frameBufferWindow->setWindowTitle(tr("Frame %1").arg(frameNumber));
                if(!renderFrame(renderTime, frameNumber, settings, renderer, viewport, frameBuffer.data(), videoEncoder, progressDialog.get()))
                    wasCanceled = true;
            }
            else if(settings->renderingRangeType() == RenderSettings::ANIMATION_INTERVAL || settings->renderingRangeType() == RenderSettings::CUSTOM_INTERVAL) {
                // Render an animation interval.
                TimePoint renderTime;
                int firstFrameNumber, numberOfFrames;
                if(settings->renderingRangeType() == RenderSettings::ANIMATION_INTERVAL) {
                    renderTime = animationSettings()->animationInterval().start();
                    firstFrameNumber = animationSettings()->timeToFrame(animationSettings()->animationInterval().start());
                    numberOfFrames = (animationSettings()->timeToFrame(animationSettings()->animationInterval().end()) - firstFrameNumber + 1);
//.........这里部分代码省略.........
开发者ID:taohonker,项目名称:Ovito,代码行数:101,代码来源:DataSet.cpp

示例7: composition

bool QWindowsInputContext::composition(HWND hwnd, LPARAM lParamIn)
{
    const int lParam = int(lParamIn);
    qCDebug(lcQpaInputMethods) << '>' << __FUNCTION__ << m_compositionContext.focusObject
        << debugComposition(lParam) << " composing=" << m_compositionContext.isComposing;
    if (m_compositionContext.focusObject.isNull() || m_compositionContext.hwnd != hwnd || !lParam)
        return false;
    const HIMC himc = ImmGetContext(m_compositionContext.hwnd);
    if (!himc)
        return false;

    QScopedPointer<QInputMethodEvent> event;
    if (lParam & (GCS_COMPSTR | GCS_COMPATTR | GCS_CURSORPOS)) {
        if (!m_compositionContext.isComposing)
            startContextComposition();
        // Some intermediate composition result. Parametrize event with
        // attribute sequence specifying the formatting of the converted part.
        int selStart, selLength;
        m_compositionContext.composition = getCompositionString(himc, GCS_COMPSTR);
        m_compositionContext.position = ImmGetCompositionString(himc, GCS_CURSORPOS, 0, 0);
        getCompositionStringConvertedRange(himc, &selStart, &selLength);
        if ((lParam & CS_INSERTCHAR) && (lParam & CS_NOMOVECARET)) {
            // make Korean work correctly. Hope this is correct for all IMEs
            selStart = 0;
            selLength = m_compositionContext.composition.size();
        }
        if (!selLength)
            selStart = 0;

        event.reset(new QInputMethodEvent(m_compositionContext.composition,
                                          intermediateMarkup(m_compositionContext.position,
                                                             m_compositionContext.composition.size(),
                                                             selStart, selLength)));
    }
    if (event.isNull())
        event.reset(new QInputMethodEvent);

    if (lParam & GCS_RESULTSTR) {
        // A fixed result, return the converted string
        event->setCommitString(getCompositionString(himc, GCS_RESULTSTR));
        endContextComposition();
    }
    const bool result = QCoreApplication::sendEvent(m_compositionContext.focusObject, event.data());
    qCDebug(lcQpaInputMethods) << '<' << __FUNCTION__ << "sending markup="
        << event->attributes().size() << " commit=" << event->commitString()
        << " to " << m_compositionContext.focusObject << " returns " << result;
    update(Qt::ImQueryAll);
    ImmReleaseContext(m_compositionContext.hwnd, himc);
    return result;
}
开发者ID:oneywang,项目名称:qtbase,代码行数:50,代码来源:qwindowsinputcontext.cpp

示例8: main

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // Set data for QSettings
    QCoreApplication::setOrganizationName("ulduzsoft");
    QCoreApplication::setOrganizationDomain("ulduzsoft.com");
    QCoreApplication::setApplicationName("spivak");

    // Init logger after crash settings
    Logger::init();

    QScopedPointer<MainWindow> p (new MainWindow());
    p.data()->show();

    QCommandLineParser parser;

    const QCommandLineOption fullScreenOption(
                QStringList() << "fs" << "fullScreen",
                "Toggle full screen"
                );

    const QCommandLineOption fileNameOption(
                QStringList() << "file" << "fileName",
                "File name to play",
                "File name to play"
                );

    const QCommandLineOption displayOption(
                QStringList() << "d" << "displayNumber",
                "Display number",
                "Screen"
                );

    parser.addOption( fullScreenOption );
    parser.addOption( fileNameOption );
    parser.addOption( displayOption );
    parser.addHelpOption();

#if defined (Q_OS_WIN)
    const QCommandLineOption showConsoleOption(
                QStringList() << "c" << "console",
                "Show debug console"
                );

    parser.addOption( showConsoleOption );
#endif

    parser.process(a);

#if defined (Q_OS_WIN)
    // Show console on Windows
    if ( parser.isSet( showConsoleOption ) )
    {
        AllocConsole();

        freopen("CONOUT$", "w", stdout);
        freopen("CONOUT$", "w", stderr);

        COORD coordInfo;
        coordInfo.X = 130;
        coordInfo.Y = 9000;

        SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coordInfo);
        SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE),ENABLE_QUICK_EDIT_MODE| ENABLE_EXTENDED_FLAGS);
    }
#endif

    const int displayNumber = parser.value(displayOption).toInt();

    if ( displayNumber && displayNumber < a.screens().size() )
    {

        const QRect resolution = a.screens()[displayNumber]
                ->availableGeometry();

        p.data()->move(
                    resolution.x(),
                    resolution.y()
                    );
    }

    if ( parser.isSet(fullScreenOption) )
    {
        p.data()->toggleFullscreen();
    }

    const QString fileName = parser.value(fileNameOption);

    if(!fileName.isEmpty()) {
        p.data()->enqueueSong(fileName);
        QObject::connect(
                    pActionHandler,
                    &ActionHandler::actionKaraokePlayerStop,
                    qApp,
                    &QApplication::quit
                    );
    }

    return a.exec();
//.........这里部分代码省略.........
开发者ID:gyunaev,项目名称:spivak,代码行数:101,代码来源:main.cpp

示例9: exportData

bool KexiCSVExport::exportData(KDbTableOrQuerySchema *tableOrQuery,
                               const Options& options, int recordCount, QTextStream *predefinedTextStream)
{
    KDbConnection* conn = tableOrQuery->connection();
    if (!conn)
        return false;

    KDbQuerySchema* query = tableOrQuery->query();
    QList<QVariant> queryParams;
    if (!query) {
        query = tableOrQuery->table()->query();
    }
    else {
        queryParams = KexiMainWindowIface::global()->currentParametersForQuery(query->id());
    }

    if (recordCount == -1)
        recordCount = KDb::recordCount(tableOrQuery, queryParams);
    if (recordCount == -1)
        return false;

//! @todo move this to non-GUI location so it can be also used via command line
//! @todo add a "finish" page with a progressbar.
//! @todo look at recordCount whether the data is really large;
//!       if so: avoid copying to clipboard (or ask user) because of system memory

//! @todo OPTIMIZATION: use fieldsExpanded(true /*UNIQUE*/)
//! @todo OPTIMIZATION? (avoid multiple data retrieving) look for already fetched data within KexiProject..

    KDbQueryColumnInfo::Vector fields(query->fieldsExpanded(KDbQuerySchema::WithInternalFields));
    QString buffer;

    QScopedPointer<QSaveFile> kSaveFile;
    QTextStream *stream = 0;
    QScopedPointer<QTextStream> kSaveFileTextStream;

    const bool copyToClipboard = options.mode == Clipboard;
    if (copyToClipboard) {
//! @todo (during exporting): enlarge bufSize by factor of 2 when it became too small
        int bufSize = qMin((recordCount < 0 ? 10 : recordCount) * fields.count() * 20, 128000);
        buffer.reserve(bufSize);
        if (buffer.capacity() < bufSize) {
            qWarning() << "Cannot allocate memory for " << bufSize
            << " characters";
            return false;
        }
    } else {
        if (predefinedTextStream) {
            stream = predefinedTextStream;
        } else {
            if (options.fileName.isEmpty()) {//sanity
                qWarning() << "Fname is empty";
                return false;
            }
            kSaveFile.reset(new QSaveFile(options.fileName));

            qDebug() << "QSaveFile Filename:" << kSaveFile->fileName();

            if (kSaveFile->open(QIODevice::WriteOnly)) {
                kSaveFileTextStream.reset(new QTextStream(kSaveFile.data()));
                stream = kSaveFileTextStream.data();
                qDebug() << "have a stream";
            }
            if (QFileDevice::NoError != kSaveFile->error() || !stream) {//sanity
                qWarning() << "Status != 0 or stream == 0";
//! @todo show error
                return false;
            }
        }
    }

//! @todo escape strings

#define _ERR \
    if (kSaveFile) { kSaveFile->cancelWriting(); } \
    return false

#define APPEND(what) \
    if (copyToClipboard) buffer.append(what); else (*stream) << (what)

// use native line ending for copying, RFC 4180 one for saving to file
#define APPEND_EOLN \
    if (copyToClipboard) { APPEND('\n'); } else { APPEND("\r\n"); }

    qDebug() << 0 << "Columns: " << query->fieldsExpanded().count();
    // 0. Cache information
    const int fieldsCount = query->fieldsExpanded().count(); //real fields count without internals
    const QByteArray delimiter(options.delimiter.left(1).toLatin1());
    const bool hasTextQuote = !options.textQuote.isEmpty();
    const QString textQuote(options.textQuote.left(1));
    const QByteArray escapedTextQuote((textQuote + textQuote).toLatin1());   //ok?
    //cache for faster checks
    QScopedArrayPointer<bool> isText(new bool[fieldsCount]);
    QScopedArrayPointer<bool> isDateTime(new bool[fieldsCount]);
    QScopedArrayPointer<bool> isTime(new bool[fieldsCount]);
    QScopedArrayPointer<bool> isBLOB(new bool[fieldsCount]);
    QScopedArrayPointer<int> visibleFieldIndex(new int[fieldsCount]);
// bool isInteger[fieldsCount]; //cache for faster checks
// bool isFloatingPoint[fieldsCount]; //cache for faster checks
    for (int i = 0; i < fieldsCount; i++) {
//.........这里部分代码省略.........
开发者ID:TheTypoMaster,项目名称:calligra,代码行数:101,代码来源:kexicsvexport.cpp

示例10: onPlaylistWidgetContextMenuRequested

void MainWindow::onPlaylistWidgetContextMenuRequested(const QPoint&)
{
   settings_t *settings = config_get_ptr();
   QScopedPointer<QMenu> menu;
   QScopedPointer<QMenu> associateMenu;
   QScopedPointer<QMenu> hiddenPlaylistsMenu;
   QScopedPointer<QAction> hideAction;
   QScopedPointer<QAction> newPlaylistAction;
   QScopedPointer<QAction> deletePlaylistAction;
   QPointer<QAction> selectedAction;
   QPoint cursorPos = QCursor::pos();
   QListWidgetItem *selectedItem = m_listWidget->itemAt(m_listWidget->viewport()->mapFromGlobal(cursorPos));
   QDir playlistDir(settings->paths.directory_playlist);
   QString playlistDirAbsPath = playlistDir.absolutePath();
   QString currentPlaylistDirPath;
   QString currentPlaylistPath;
   QString currentPlaylistFileName;
   QFile currentPlaylistFile;
   QByteArray currentPlaylistFileNameArray;
   QFileInfo currentPlaylistFileInfo;
   QMap<QString, const core_info_t*> coreList;
   core_info_list_t *core_info_list = NULL;
   union string_list_elem_attr attr = {0};
   struct string_list *stnames = NULL;
   struct string_list *stcores = NULL;
   unsigned i = 0;
   int j = 0;
   size_t found = 0;
   const char *currentPlaylistFileNameData = NULL;
   char new_playlist_names[PATH_MAX_LENGTH];
   char new_playlist_cores[PATH_MAX_LENGTH];
   bool specialPlaylist = false;
   bool foundHiddenPlaylist = false;

   new_playlist_names[0] = new_playlist_cores[0] = '\0';

   stnames = string_split(settings->arrays.playlist_names, ";");
   stcores = string_split(settings->arrays.playlist_cores, ";");

   if (selectedItem)
   {
      currentPlaylistPath = selectedItem->data(Qt::UserRole).toString();
      currentPlaylistFile.setFileName(currentPlaylistPath);

      currentPlaylistFileInfo = QFileInfo(currentPlaylistPath);
      currentPlaylistFileName = currentPlaylistFileInfo.fileName();
      currentPlaylistDirPath = currentPlaylistFileInfo.absoluteDir().absolutePath();

      currentPlaylistFileNameArray.append(currentPlaylistFileName);
      currentPlaylistFileNameData = currentPlaylistFileNameArray.constData();
   }

   menu.reset(new QMenu(this));
   menu->setObjectName("menu");

   hiddenPlaylistsMenu.reset(new QMenu(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_HIDDEN_PLAYLISTS), this));
   newPlaylistAction.reset(new QAction(QString(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_NEW_PLAYLIST)) + "...", this));

   hiddenPlaylistsMenu->setObjectName("hiddenPlaylistsMenu");

   menu->addAction(newPlaylistAction.data());

   if (currentPlaylistFile.exists())
   {
      deletePlaylistAction.reset(new QAction(QString(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_DELETE_PLAYLIST)) + "...", this));
      menu->addAction(deletePlaylistAction.data());
   }

   if (selectedItem)
   {
      hideAction.reset(new QAction(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_HIDE), this));
      menu->addAction(hideAction.data());
   }

   for (j = 0; j < m_listWidget->count(); j++)
   {
      QListWidgetItem *item = m_listWidget->item(j);
      bool hidden = m_listWidget->isItemHidden(item);

      if (hidden)
      {
         QAction *action = hiddenPlaylistsMenu->addAction(item->text());
         action->setProperty("row", j);
         action->setProperty("core_path", item->data(Qt::UserRole).toString());
         foundHiddenPlaylist = true;
      }
   }

   if (!foundHiddenPlaylist)
   {
      QAction *action = hiddenPlaylistsMenu->addAction(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_NONE));
      action->setProperty("row", -1);
   }

   menu->addMenu(hiddenPlaylistsMenu.data());

   if (currentPlaylistDirPath != playlistDirAbsPath)
   {
      /* special playlists like history etc. can't have an association */
      specialPlaylist = true;
//.........这里部分代码省略.........
开发者ID:gouchi,项目名称:RetroArch,代码行数:101,代码来源:playlist.cpp

示例11: rendererReady

 Q_SLOT void rendererReady() {
    m_renderer.reset(m_future.result());
    m_renderer->moveToThread(thread());
    setRenderer(m_renderer.data());
 }
开发者ID:KubaO,项目名称:stackoverflown,代码行数:5,代码来源:main.cpp

示例12: loadHtml

void QgsComposerHtml::loadHtml( const bool useCache, const QgsExpressionContext *context )
{
  if ( !mWebPage )
  {
    return;
  }

  const QgsExpressionContext* evalContext = context;
  QScopedPointer< QgsExpressionContext > scopedContext;
  if ( !evalContext )
  {
    scopedContext.reset( createExpressionContext() );
    evalContext = scopedContext.data();
  }

  QString loadedHtml;
  switch ( mContentMode )
  {
    case QgsComposerHtml::Url:
    {

      QString currentUrl = mUrl.toString();

      //data defined url set?
      QVariant exprVal;
      if ( dataDefinedEvaluate( QgsComposerObject::SourceUrl, exprVal, *evalContext ) )
      {
        currentUrl = exprVal.toString().trimmed();
        QgsDebugMsg( QString( "exprVal Source Url:%1" ).arg( currentUrl ) );
      }
      if ( currentUrl.isEmpty() )
      {
        return;
      }
      if ( !( useCache && currentUrl == mLastFetchedUrl ) )
      {
        loadedHtml = fetchHtml( QUrl( currentUrl ) );
        mLastFetchedUrl = currentUrl;
      }
      else
      {
        loadedHtml = mFetchedHtml;
      }

      break;
    }
    case QgsComposerHtml::ManualHtml:
      loadedHtml = mHtml;
      break;
  }

  //evaluate expressions
  if ( mEvaluateExpressions )
  {
    loadedHtml = QgsExpression::replaceExpressionText( loadedHtml, evalContext, nullptr, mDistanceArea );
  }

  mLoaded = false;

  //reset page size. otherwise viewport size increases but never decreases again
  mWebPage->setViewportSize( QSize( maxFrameWidth() * mHtmlUnitsToMM, 0 ) );

  //set html, using the specified url as base if in Url mode
  mWebPage->mainFrame()->setHtml( loadedHtml, mContentMode == QgsComposerHtml::Url ? QUrl( mActualFetchedUrl ) : QUrl() );

  //set user stylesheet
  QWebSettings* settings = mWebPage->settings();
  if ( mEnableUserStylesheet && ! mUserStylesheet.isEmpty() )
  {
    QByteArray ba;
    ba.append( mUserStylesheet.toUtf8() );
    QUrl cssFileURL = QUrl( "data:text/css;charset=utf-8;base64," + ba.toBase64() );
    settings->setUserStyleSheetUrl( cssFileURL );
  }
  else
  {
    settings->setUserStyleSheetUrl( QUrl() );
  }

  while ( !mLoaded )
  {
    qApp->processEvents();
  }

  recalculateFrameSizes();
  //trigger a repaint
  emit contentsChanged();
}
开发者ID:Antoviscomi,项目名称:QGIS,代码行数:88,代码来源:qgscomposerhtml.cpp

示例13: shaderCache

// The address returned here will only be valid until next time this function is called.
// The program is return bound.
QGLEngineShaderProg *QGLEngineSharedShaders::findProgramInCache(const QGLEngineShaderProg &prog)
{
    for (int i = 0; i < cachedPrograms.size(); ++i) {
        QGLEngineShaderProg *cachedProg = cachedPrograms[i];
        if (*cachedProg == prog) {
            // Move the program to the top of the list as a poor-man's cache algo
            cachedPrograms.move(i, 0);
            cachedProg->program->bind();
            return cachedProg;
        }
    }

    QScopedPointer<QGLEngineShaderProg> newProg;

    do {
        QByteArray fragSource;
        // Insert the custom stage before the srcPixel shader to work around an ATI driver bug
        // where you cannot forward declare a function that takes a sampler as argument.
        if (prog.srcPixelFragShader == CustomImageSrcFragmentShader)
            fragSource.append(prog.customStageSource);
        fragSource.append(qShaderSnippets[prog.mainFragShader]);
        fragSource.append(qShaderSnippets[prog.srcPixelFragShader]);
        if (prog.compositionFragShader)
            fragSource.append(qShaderSnippets[prog.compositionFragShader]);
        if (prog.maskFragShader)
            fragSource.append(qShaderSnippets[prog.maskFragShader]);

        QByteArray vertexSource;
        vertexSource.append(qShaderSnippets[prog.mainVertexShader]);
        vertexSource.append(qShaderSnippets[prog.positionVertexShader]);

        QScopedPointer<QGLShaderProgram> shaderProgram(new QGLShaderProgram(ctxGuard.context(), 0));

        CachedShader shaderCache(fragSource, vertexSource);
        bool inCache = shaderCache.load(shaderProgram.data(), ctxGuard.context());

        if (!inCache) {

            QScopedPointer<QGLShader> fragShader(new QGLShader(QGLShader::Fragment, ctxGuard.context(), 0));
            QByteArray description;
#if defined(QT_DEBUG)
            // Name the shader for easier debugging
            description.append("Fragment shader: main=");
            description.append(snippetNameStr(prog.mainFragShader));
            description.append(", srcPixel=");
            description.append(snippetNameStr(prog.srcPixelFragShader));
            if (prog.compositionFragShader) {
                description.append(", composition=");
                description.append(snippetNameStr(prog.compositionFragShader));
            }
            if (prog.maskFragShader) {
                description.append(", mask=");
                description.append(snippetNameStr(prog.maskFragShader));
            }
            fragShader->setObjectName(QString::fromLatin1(description));
#endif
            if (!fragShader->compileSourceCode(fragSource)) {
                qWarning() << "Warning:" << description << "failed to compile!";
                break;
            }

            QScopedPointer<QGLShader> vertexShader(new QGLShader(QGLShader::Vertex, ctxGuard.context(), 0));
#if defined(QT_DEBUG)
            // Name the shader for easier debugging
            description.clear();
            description.append("Vertex shader: main=");
            description.append(snippetNameStr(prog.mainVertexShader));
            description.append(", position=");
            description.append(snippetNameStr(prog.positionVertexShader));
            vertexShader->setObjectName(QString::fromLatin1(description));
#endif
            if (!vertexShader->compileSourceCode(vertexSource)) {
                qWarning() << "Warning:" << description << "failed to compile!";
                break;
            }

            shaders.append(vertexShader.data());
            shaders.append(fragShader.data());
            shaderProgram->addShader(vertexShader.take());
            shaderProgram->addShader(fragShader.take());

            // We have to bind the vertex attribute names before the program is linked:
            shaderProgram->bindAttributeLocation("vertexCoordsArray", QT_VERTEX_COORDS_ATTR);
            if (prog.useTextureCoords)
                shaderProgram->bindAttributeLocation("textureCoordArray", QT_TEXTURE_COORDS_ATTR);
            if (prog.useOpacityAttribute)
                shaderProgram->bindAttributeLocation("opacityArray", QT_OPACITY_ATTR);
            if (prog.usePmvMatrixAttribute) {
                shaderProgram->bindAttributeLocation("pmvMatrix1", QT_PMV_MATRIX_1_ATTR);
                shaderProgram->bindAttributeLocation("pmvMatrix2", QT_PMV_MATRIX_2_ATTR);
                shaderProgram->bindAttributeLocation("pmvMatrix3", QT_PMV_MATRIX_3_ATTR);
            }
        }

        newProg.reset(new QGLEngineShaderProg(prog));
        newProg->program = shaderProgram.take();

        newProg->program->link();
//.........这里部分代码省略.........
开发者ID:Blizzard,项目名称:qt4,代码行数:101,代码来源:qglengineshadermanager.cpp

示例14: headerStream

Database* KeePass2Reader::readDatabase(QIODevice* device, const CompositeKey& key)
{
    QScopedPointer<Database> db(new Database());
    m_db = db.data();
    QPointer<QIODevice> m_device = device;
    m_error = false;
    m_errorStr = QString();
    m_headerEnd = false;
    m_xmlData.clear();
    m_masterSeed.clear();
    m_transformSeed.clear();
    m_encryptionIV.clear();
    m_streamStartBytes.clear();
    m_protectedStreamKey.clear();

    StoreDataStream headerStream(m_device);
    headerStream.open(QIODevice::ReadOnly);
    m_headerStream = &headerStream;

    bool ok;

    quint32 signature1 = Endian::readUInt32(m_headerStream, KeePass2::BYTEORDER, &ok);
    if (!ok || signature1 != KeePass2::SIGNATURE_1) {
        raiseError(tr("Not a KeePass database."));
        return Q_NULLPTR;
    }

    quint32 signature2 = Endian::readUInt32(m_headerStream, KeePass2::BYTEORDER, &ok);
    if (!ok || signature2 != KeePass2::SIGNATURE_2) {
        raiseError(tr("Not a KeePass database."));
        return Q_NULLPTR;
    }

    quint32 version = Endian::readUInt32(m_headerStream, KeePass2::BYTEORDER, &ok)
            & KeePass2::FILE_VERSION_CRITICAL_MASK;
    quint32 maxVersion = KeePass2::FILE_VERSION & KeePass2::FILE_VERSION_CRITICAL_MASK;
    if (!ok || (version < KeePass2::FILE_VERSION_MIN) || (version > maxVersion)) {
        raiseError(tr("Unsupported KeePass database version."));
        return Q_NULLPTR;
    }

    while (readHeaderField() && !hasError()) {
    }

    headerStream.close();

    // check if all required headers were present
    if (m_masterSeed.isEmpty() || m_transformSeed.isEmpty() || m_encryptionIV.isEmpty()
            || m_streamStartBytes.isEmpty() || m_protectedStreamKey.isEmpty()
            || m_db->cipher().isNull()) {
        raiseError("");
        return Q_NULLPTR;
    }

    m_db->setKey(key, m_transformSeed, false);

    CryptoHash hash(CryptoHash::Sha256);
    hash.addData(m_masterSeed);
    hash.addData(m_db->transformedMasterKey());
    QByteArray finalKey = hash.result();

    SymmetricCipherStream cipherStream(m_device, SymmetricCipher::Aes256, SymmetricCipher::Cbc,
                                       SymmetricCipher::Decrypt, finalKey, m_encryptionIV);
    cipherStream.open(QIODevice::ReadOnly);

    QByteArray realStart = cipherStream.read(32);

    if (realStart != m_streamStartBytes) {
        raiseError(tr("Wrong key or database file is corrupt."));
        return Q_NULLPTR;
    }

    HashedBlockStream hashedStream(&cipherStream);
    hashedStream.open(QIODevice::ReadOnly);

    QIODevice* xmlDevice;
    QScopedPointer<QtIOCompressor> ioCompressor;

    if (m_db->compressionAlgo() == Database::CompressionNone) {
        xmlDevice = &hashedStream;
    }
    else {
        ioCompressor.reset(new QtIOCompressor(&hashedStream));
        ioCompressor->setStreamFormat(QtIOCompressor::GzipFormat);
        ioCompressor->open(QIODevice::ReadOnly);
        xmlDevice = ioCompressor.data();
    }

    KeePass2RandomStream randomStream(m_protectedStreamKey);

    QScopedPointer<QBuffer> buffer;

    if (m_saveXml) {
        m_xmlData = xmlDevice->readAll();
        buffer.reset(new QBuffer(&m_xmlData));
        buffer->open(QIODevice::ReadOnly);
        xmlDevice = buffer.data();
    }

    KeePass2XmlReader xmlReader;
//.........这里部分代码省略.........
开发者ID:DiscoStarslayer,项目名称:keepassbb10,代码行数:101,代码来源:KeePass2Reader.cpp

示例15: testFormat

void TestGooString::testFormat()
{
    {
        const QScopedPointer<GooString> goo(GooString::format("{0:d},{1:x}", 1, 0xF));
        QCOMPARE(goo->getCString(), "1,f");
    }
    {
        const QScopedPointer<GooString> goo(GooString::format("{0:d},{0:x},{0:X},{0:o},{0:b},{0:w}", 0xA));
        QCOMPARE(goo->getCString(), "10,a,A,12,1010,          ");
    }
    {
        const QScopedPointer<GooString> goo(GooString::format("{0:d},{0:x},{0:X},{0:o},{0:b}", -0xA));
        QCOMPARE(goo->getCString(), "-10,-a,-A,-12,-1010");
    }
    {
        const QScopedPointer<GooString> goo(GooString::format("{0:c}{1:c}{2:c}{3:c}",
            'T', (char)'E', (short)'S', (int)'T'));
        QCOMPARE(goo->getCString(), "TEST");

        const QScopedPointer<GooString> goo2(GooString::format("{0:s} {1:t}", "TEST", goo.data()));
        QCOMPARE(goo2->getCString(), "TEST TEST");
    }
    {
        const QScopedPointer<GooString> goo(GooString::format("{0:ud} {1:d} {2:d}",
            UINT_MAX, INT_MAX, INT_MIN));
        const QByteArray expected = QString("%1 %2 %3").arg(UINT_MAX).arg(INT_MAX).arg(INT_MIN).toLatin1();
        QCOMPARE(goo->getCString(), expected.constData());
    }
    {
        const QScopedPointer<GooString> goo(GooString::format("{0:uld} {1:ld} {2:ld}",
            ULONG_MAX, LONG_MAX, LONG_MIN));
        const QByteArray expected = QString("%1 %2 %3").arg(ULONG_MAX).arg(LONG_MAX).arg(LONG_MIN).toLatin1();
        QCOMPARE(goo->getCString(), expected.constData());
    }
    {
        const QScopedPointer<GooString> goo(GooString::format("{0:ulld} {1:lld} {2:lld}",
            ULLONG_MAX, LLONG_MAX, LLONG_MIN));
        const QByteArray expected = QString("%1 %2 %3").arg(ULLONG_MAX).arg(LLONG_MAX).arg(LLONG_MIN).toLatin1();
        QCOMPARE(goo->getCString(), expected.constData());
    }
    {
        const QScopedPointer<GooString> gooD(GooString::format("{0:.1f} {0:.1g} {0:.1gs} | {1:.1f} {1:.1g} {1:.1gs}", 1., .012));
        const QScopedPointer<GooString> gooF(GooString::format("{0:.1f} {0:.1g} {0:.1gs} | {1:.1f} {1:.1g} {1:.1gs}", 1.f, .012f));
        QCOMPARE(gooD->getCString(), "1.0 1 1 | 0.0 0 0.01");
        QCOMPARE(gooF->getCString(), "1.0 1 1 | 0.0 0 0.01");
    }
    {
        const QScopedPointer<GooString> goo(GooString::format("{0:.4f} {0:.4g} {0:.4gs}", .012));
        QCOMPARE(goo->getCString(), "0.0120 0.012 0.012");
    }
    {
        const QScopedPointer<GooString> goo(GooString::format("{{ SomeText {0:d} }}", 1));
        QCOMPARE(goo->getCString(), "{ SomeText 1 }");
    }
    {
        const QScopedPointer<GooString> goo(GooString::format("{{{{ {{ SomeText {0:d}", 2));
        QCOMPARE(goo->getCString(), "{{ { SomeText 2");
    }
    {
        const QScopedPointer<GooString> goo(GooString::format("SomeText {0:d} }} }}}}", 3));
        QCOMPARE(goo->getCString(), "SomeText 3 } }}");
    }
}
开发者ID:BlueBrain,项目名称:Poppler,代码行数:63,代码来源:check_goostring.cpp


注:本文中的QScopedPointer::data方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。