void MediaControls::updateVolume()
{
    m_muteButton->updateDisplayType();
    // Invalidate the mute button because it paints differently according to volume.
    if (LayoutObject* layoutObject = m_muteButton->layoutObject())
        layoutObject->setShouldDoFullPaintInvalidation();

    if (mediaElement().muted())
        m_volumeSlider->setVolume(0);
    else
        m_volumeSlider->setVolume(mediaElement().volume());

    // Update the visibility of our audio elements.
    // We never want the volume slider if there's no audio.
    // If there is audio, then we want it unless hiding audio is enabled and
    // we prefer to hide it.
    BatchedControlUpdate batch(this);
    m_volumeSlider->setIsWanted(mediaElement().hasAudio()
        && !(m_allowHiddenVolumeControls && preferHiddenVolumeControls(document())));

    // The mute button is a little more complicated.  If enableNewMediaPlaybackUi
    // is true, then we choose to hide or show the mute button to save space.
    // If enableNew* is not set, then we never touch the mute button, and
    // instead leave it to the CSS.
    // Note that this is why m_allowHiddenVolumeControls isn't rolled into prefer...().
    if (m_allowHiddenVolumeControls) {
        // If there is no audio track, then hide the mute button.  If there
        // is an audio track, then we always show the mute button unless
        // we prefer to hide it and the media isn't muted.  If it's muted,
        // then we show it to let the user unmute it.  In this case, we don't
        // want to re-hide the mute button later.
        m_keepMuteButton |= mediaElement().muted();
        m_muteButton->setIsWanted(mediaElement().hasAudio()
            && (!preferHiddenVolumeControls(document()) || m_keepMuteButton));
    }

    // Invalidate the volume slider because it paints differently according to volume.
    if (LayoutObject* layoutObject = m_volumeSlider->layoutObject())
        layoutObject->setShouldDoFullPaintInvalidation();
}
TEST_F(DynSSSPGTest, testDynamicBFS_1edge) {
/* Graph:
    0    3   6
     \  / \ /
      2    5
     /  \ / \
    1    4   7
 */
	count n = 8;
	Graph G(n);

	G.addEdge(0, 2);
	G.addEdge(1, 2);
	G.addEdge(2, 3);
	G.addEdge(2, 4);
	G.addEdge(3, 5);
	G.addEdge(4, 5);
	G.addEdge(5, 6);
	G.addEdge(5, 7);

	BFS bfs(G, 0);
	bfs.run();
	DynBFS dbfs(G, 0);
	dbfs.run();
	std::vector<GraphEvent> batch(1);
	batch[0].type = GraphEvent::EDGE_ADDITION;
	batch[0].u = 0;
	batch[0].v = 6;
	batch[0].w = 1.0;
	for (GraphEvent edge : batch) {
		G.addEdge(edge.u, edge.v, edge.w);
	}
	dbfs.update(batch);
	bfs.run();
	G.forNodes([&] (node i) {
		EXPECT_EQ(bfs.distance(i), dbfs.distance(i));
		EXPECT_EQ(bfs.numberOfPaths(i), dbfs.numberOfPaths(i));
	});
}
示例#3
0
void GrSWMaskHelper::DrawToTargetWithPathMask(GrTexture* texture,
                                              GrDrawContext* drawContext,
                                              const GrPaint* paint,
                                              const GrUserStencilSettings* userStencilSettings,
                                              const GrClip& clip,
                                              GrColor color,
                                              const SkMatrix& viewMatrix,
                                              const SkIRect& rect) {
    SkMatrix invert;
    if (!viewMatrix.invert(&invert)) {
        return;
    }

    SkRect dstRect = SkRect::MakeLTRB(SK_Scalar1 * rect.fLeft,
                                      SK_Scalar1 * rect.fTop,
                                      SK_Scalar1 * rect.fRight,
                                      SK_Scalar1 * rect.fBottom);

    // We use device coords to compute the texture coordinates. We take the device coords and apply
    // a translation so that the top-left of the device bounds maps to 0,0, and then a scaling
    // matrix to normalized coords.
    SkMatrix maskMatrix;
    maskMatrix.setIDiv(texture->width(), texture->height());
    maskMatrix.preTranslate(SkIntToScalar(-rect.fLeft), SkIntToScalar(-rect.fTop));

    GrPipelineBuilder pipelineBuilder(*paint, drawContext->isUnifiedMultisampled());
    pipelineBuilder.setRenderTarget(drawContext->accessRenderTarget());
    pipelineBuilder.setUserStencil(userStencilSettings);

    pipelineBuilder.addCoverageFragmentProcessor(
                         GrSimpleTextureEffect::Create(texture,
                                                       maskMatrix,
                                                       GrTextureParams::kNone_FilterMode,
                                                       kDevice_GrCoordSet))->unref();

    SkAutoTUnref<GrDrawBatch> batch(GrRectBatchFactory::CreateNonAAFill(color, SkMatrix::I(),
                                                                        dstRect, nullptr, &invert));
    drawContext->drawBatch(pipelineBuilder, clip, batch);
}
示例#4
0
bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
    CDBBatch batch(db);
    size_t count = 0;
    size_t changed = 0;
    for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
        if (it->second.flags & CCoinsCacheEntry::DIRTY) {
            if (it->second.coins.IsPruned())
                batch.Erase(std::make_pair(DB_COINS, it->first));
            else
                batch.Write(std::make_pair(DB_COINS, it->first), it->second.coins);
            changed++;
        }
        count++;
        CCoinsMap::iterator itOld = it++;
        mapCoins.erase(itOld);
    }
    if (!hashBlock.IsNull())
        batch.Write(DB_BEST_BLOCK, hashBlock);

    LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
    return db.WriteBatch(batch);
}
示例#5
0
inline
void GrAtlasTextBlob::flushRun(GrDrawContext* dc, GrPipelineBuilder* pipelineBuilder,
                               const GrClip& clip, int run, const SkMatrix& viewMatrix, SkScalar x,
                               SkScalar y, GrColor color,
                               const SkPaint& skPaint, const SkSurfaceProps& props,
                               const GrDistanceFieldAdjustTable* distanceAdjustTable,
                               GrBatchFontCache* cache) {
    for (int subRun = 0; subRun < fRuns[run].fSubRunInfo.count(); subRun++) {
        const Run::SubRunInfo& info = fRuns[run].fSubRunInfo[subRun];
        int glyphCount = info.glyphCount();
        if (0 == glyphCount) {
            continue;
        }

        SkAutoTUnref<GrDrawBatch> batch(this->createBatch(info, glyphCount, run,
                                                          subRun, viewMatrix, x, y, color,
                                                          skPaint, props,
                                                          distanceAdjustTable, dc->isGammaCorrect(),
                                                          cache));
        dc->drawBatch(*pipelineBuilder, clip, batch);
    }
}
示例#6
0
void
CollectionScanner::Scanner::readBatchFile( const QString &path )
{
    QFile batchFile( path );

    if( !batchFile.exists() )
        error( tr( "File \"%1\" not found." ).arg( path ) );

    if( !batchFile.open( QIODevice::ReadOnly ) )
        error( tr( "Could not open file \"%1\"." ).arg( path ) );

    BatchFile batch( path );
    foreach( const QString &str, batch.directories() )
    {
        m_folders.append( str );
    }

    foreach( const CollectionScanner::BatchFile::TimeDefinition &def, batch.timeDefinitions() )
    {
        m_mTimes.insert( def.first, def.second );
    }
}
示例#7
0
void MediaControls::reset() {
  EventDispatchForbiddenScope::AllowUserAgentEvents allowEventsInShadow;
  BatchedControlUpdate batch(this);

  const double duration = mediaElement().duration();
  m_durationDisplay->setTextContent(
      LayoutTheme::theme().formatMediaControlsTime(duration));
  m_durationDisplay->setCurrentValue(duration);

  // Show everything that we might hide.
  // If we don't have a duration, then mark it to be hidden.  For the
  // old UI case, want / don't want is the same as show / hide since
  // it is never marked as not fitting.
  m_durationDisplay->setIsWanted(std::isfinite(duration));
  m_currentTimeDisplay->setIsWanted(true);
  m_timeline->setIsWanted(true);

  // If the player has entered an error state, force it into the paused state.
  if (mediaElement().error())
    mediaElement().pause();

  updatePlayState();

  updateCurrentTimeDisplay();

  m_timeline->setDuration(duration);
  m_timeline->setPosition(mediaElement().currentTime());

  onVolumeChange();
  onTextTracksAddedOrRemoved();

  m_fullscreenButton->setIsWanted(shouldShowFullscreenButton(mediaElement()));

  refreshCastButtonVisibilityWithoutUpdate();

  m_downloadButton->setIsWanted(
      m_downloadButton->shouldDisplayDownloadButton());
}
示例#8
0
void EditorInterface::makeBatch(QString& batchFileName)
{
	FNTRACE("", "EditorInterface", "batchFileName", batchFileName);

	if (batchFileName.endsWith(".bat", Qt::CaseInsensitive))
		fileName = batchFileName.left(batchFileName.length()-4);
	else
		fileName = batchFileName;

	makeRelativePaths();

	batchFileName = fileName+".bat";
	QString debugFileName = fileName + "_debug.txt";

	QStringList args = makeArgs();

	QFile batchFile(batchFileName);
	if (!batchFile.open(QIODevice::WriteOnly | QIODevice::Text))
		ETHROW(Exception(QString("Failed to open %1 for writing").arg(batchFileName)));
	QTextStream batch(&batchFile);

	batch << "@echo off\n";
	if (QDir::drives().size()>1)
		batch << editorDir.absolutePath().left(2) << "\n";
	batch << "cd \"" << editorDir.absolutePath() << "\"\n" << editorName;
	for (QStringList::iterator arg = args.begin(); arg != args.end(); ++arg)
	{
		batch << ' ';
		if (arg->contains(' '))
			batch << '"'+(*arg)+'"';
		else
			batch << (*arg);
	}
	batch << " > \"" << debugFileName << "\"\n"
			"If ERRORLEVEL 0 goto DONE\n"
			"pause\n"
			":DONE\n";
}
bool GrAALinearizingConvexPathRenderer::onDrawPath(GrDrawTarget* target,
                                                   GrPipelineBuilder* pipelineBuilder,
                                                   GrColor color,
                                                   const SkMatrix& vm,
                                                   const SkPath& path,
                                                   const GrStrokeInfo& stroke,
                                                   bool antiAlias) {
    if (path.isEmpty()) {
        return true;
    }
    AAFlatteningConvexPathBatch::Geometry geometry;
    geometry.fColor = color;
    geometry.fViewMatrix = vm;
    geometry.fPath = path;
    geometry.fStrokeWidth = stroke.isFillStyle() ? -1.0f : stroke.getWidth();
    geometry.fJoin = stroke.isFillStyle() ? SkPaint::Join::kMiter_Join : stroke.getJoin();
    geometry.fMiterLimit = stroke.getMiter();

    SkAutoTUnref<GrBatch> batch(AAFlatteningConvexPathBatch::Create(geometry));
    target->drawBatch(pipelineBuilder, batch);

    return true;
}
void AccountSettings::deleteMessages()
{
    if (!deleteMessageIds.isEmpty()) {
        // Process the next batch
        QMailMessageIdList batch(deleteMessageIds.mid(0, deleteBatchSize));
        if (deleteMessageIds.count() > deleteBatchSize) {
            deleteMessageIds = deleteMessageIds.mid(deleteBatchSize);
        } else {
            deleteMessageIds.clear();
        }

        QMailStore::instance()->removeMessages(QMailMessageKey::id(batch), QMailStore::NoRemovalRecord);
        deleteProgress += batch.count();

        statusDisplay->setProgress(deleteProgress, deleteProgress + deleteMessageIds.count());
        QTimer::singleShot(0, this, SLOT(deleteMessages()));
    } else {
        // Remove the account now
        QMailStore::instance()->removeAccount(deleteAccountId);

        statusDisplay->setVisible(false);
    }
}
示例#11
0
int bench(int argc, char **argv, bool main_bench) {
    for (int arg = 0; arg < argc; ++arg) {
        if (!strncmp("--batch=", argv[arg], 8))
            SAFE(batch(argv[arg] + 8, bench), CRIT);
        else if (!strncmp("--dir=", argv[arg], 6))
            dir = str2dir(argv[arg] + 6);
        else if (!strncmp("--dt=", argv[arg], 5))
            dt = str2dt(argv[arg] + 5);
        else if (!strncmp("--tag=", argv[arg], 6))
            tag = str2tag(argv[arg] + 6);
        else if (!strncmp("--axis=", argv[arg], 7))
            axis = atoi(argv[arg] + 7);
        else if (!strncmp("--group=", argv[arg], 8))
            group = atoi(argv[arg] + 8);
        else if (!strncmp("--match=", argv[arg], 8))
            pattern = argv[arg] + 8;
        else if (!strncmp("--mode=", argv[0], 7))
            bench_mode = str2bench_mode(argv[0] + 7);
        else if (!strcmp("--reset", argv[arg]))
            reset_parameters();
        else if (!strncmp("-v", argv[arg], 2))
            verbose = atoi(argv[arg] + 2);
        else if (!strncmp("--verbose=", argv[arg], 10))
            verbose = atoi(argv[arg] + 10);
        else {
            if (!strncmp("--", argv[arg], 2)) {
                fprintf(stderr, "driver: unknown option: `%s`, exiting...\n",
                        argv[arg]);
                exit(2);
            }
            dims = str2dims(argv[arg]);
            check_correctness();
        }
    }

    return OK;
}
示例#12
0
SmartPointer<Batch> Batch::Cube(const Box3f& box)
{
	SmartPointer<Vector> vertices;
	vertices.reset(new Vector(6*4*3));float* V=vertices->mem();
	
	SmartPointer<Vector> normals;
	normals.reset (new Vector(6*4*3));float* N=normals->mem();

	static float n[6][3]   = {{-1.0, 0.0, 0.0},{0.0, 1.0, 0.0},{1.0, 0.0, 0.0},{0.0, -1.0, 0.0},{0.0, 0.0, 1.0},{0.0, 0.0, -1.0}};
	static int faces[6][4] = {{0, 1, 2, 3},{3, 2, 6, 7},{7, 6, 5, 4},{4, 5, 1, 0},{5, 6, 2, 1},{7, 4, 0, 3}};

	float v[8][3];
	v[0][0] = v[1][0] = v[2][0] = v[3][0] = v[0][1] = v[1][1] = v[4][1] = v[5][1] = v[0][2] = v[3][2] = v[4][2] = v[7][2] = 0;
	v[4][0] = v[5][0] = v[6][0] = v[7][0] = v[2][1] = v[3][1] = v[6][1] = v[7][1] = v[1][2] = v[2][2] = v[5][2] = v[6][2] = 1;

	for (int i = 5; i >= 0; i--) 
	{
		float* v0=&v[faces[i][0]][0];* V++=v0[0]; *V++=v0[1]; *V++=v0[2];
		float* v1=&v[faces[i][1]][0];* V++=v1[0]; *V++=v1[1]; *V++=v1[2];
		float* v2=&v[faces[i][2]][0];* V++=v2[0]; *V++=v2[1]; *V++=v2[2];
		float* v3=&v[faces[i][3]][0];* V++=v3[0]; *V++=v3[1]; *V++=v3[2];

		float* normal=&n[i][0];
		
		*N++=normal[0];*N++=normal[1];*N++=normal[2];
		*N++=normal[0];*N++=normal[1];*N++=normal[2];
		*N++=normal[0];*N++=normal[1];*N++=normal[2];
		*N++=normal[0];*N++=normal[1];*N++=normal[2];
	}

	SmartPointer<Batch> batch(new Batch);
	batch->primitive=Batch::QUADS;
	batch->matrix=Mat4f::translate(box.p1)*Mat4f::scale(box.size());
	batch->vertices = vertices;
	batch->normals  = normals;
	return batch;
}
nsresult
MediaEngineGonkVideoSource::UpdatePhotoOrientation()
{
  MOZ_ASSERT(NS_IsMainThread());

  hal::ScreenConfiguration config;
  hal::GetCurrentScreenConfiguration(&config);

  // The rotation angle is clockwise.
  int orientation = 0;
  switch (config.orientation()) {
    case eScreenOrientation_PortraitPrimary:
      orientation = 0;
      break;
    case eScreenOrientation_PortraitSecondary:
      orientation = 180;
      break;
   case eScreenOrientation_LandscapePrimary:
      orientation = 270;
      break;
   case eScreenOrientation_LandscapeSecondary:
      orientation = 90;
      break;
  }

  // Front camera is inverse angle comparing to back camera.
  orientation = (mBackCamera ? orientation : (-orientation));

  ICameraControlParameterSetAutoEnter batch(mCameraControl);
  // It changes the orientation value in EXIF information only.
  mCameraControl->Set(CAMERA_PARAM_PICTURE_ROTATION, orientation);

  mOrientationChanged = false;

  return NS_OK;
}
void MediaControls::reset()
{
    const bool useNewUi = RuntimeEnabledFeatures::newMediaPlaybackUiEnabled();
    BatchedControlUpdate batch(this);

    m_allowHiddenVolumeControls = useNewUi;

    const double duration = mediaElement().duration();
    m_durationDisplay->setInnerText(LayoutTheme::theme().formatMediaControlsTime(duration), ASSERT_NO_EXCEPTION);
    m_durationDisplay->setCurrentValue(duration);

    if (useNewUi) {
        // Show everything that we might hide.
        // If we don't have a duration, then mark it to be hidden.  For the
        // old UI case, want / don't want is the same as show / hide since
        // it is never marked as not fitting.
        m_durationDisplay->setIsWanted(std::isfinite(duration));
        m_currentTimeDisplay->setIsWanted(true);
        m_timeline->setIsWanted(true);
    }

    updatePlayState();

    updateCurrentTimeDisplay();

    m_timeline->setDuration(duration);
    m_timeline->setPosition(mediaElement().currentTime());

    updateVolume();

    refreshClosedCaptionsButtonVisibility();

    m_fullScreenButton->setIsWanted(shouldShowFullscreenButton(mediaElement()));

    refreshCastButtonVisibilityWithoutUpdate();
}
示例#15
0
    void BatchWriteExec::executeBatch( const BatchedCommandRequest& clientRequest,
                                       BatchedCommandResponse* clientResponse ) {

        BatchWriteOp batchOp;
        batchOp.initClientRequest( &clientRequest );

        // Current batch status
        bool refreshedTargeter = false;
        int rounds = 0;
        int numCompletedOps = 0;
        int numRoundsWithoutProgress = 0;

        while ( !batchOp.isFinished() ) {

            //
            // Get child batches to send using the targeter
            //
            // Targeting errors can be caused by remote metadata changing (the collection could have
            // been dropped and recreated, for example with a new shard key).  If a remote metadata
            // change occurs *before* a client sends us a batch, we need to make sure that we don't
            // error out just because we're staler than the client - otherwise mongos will be have
            // unpredictable behavior.
            //
            // (If a metadata change happens *during* or *after* a client sends us a batch, however,
            // we make no guarantees about delivery.)
            //
            // For this reason, we don't record targeting errors until we've refreshed our targeting
            // metadata at least once *after* receiving the client batch - at that point, we know:
            //
            // 1) our new metadata is the same as the metadata when the client sent a batch, and so
            //    targeting errors are real.
            // OR
            // 2) our new metadata is a newer version than when the client sent a batch, and so
            //    the metadata must have changed after the client batch was sent.  We don't need to
            //    deliver in this case, since for all the client knows we may have gotten the batch
            //    exactly when the metadata changed.
            //

            vector<TargetedWriteBatch*> childBatches;

            // If we've already had a targeting error, we've refreshed the metadata once and can
            // record target errors definitively.
            bool recordTargetErrors = refreshedTargeter;
            Status targetStatus = batchOp.targetBatch( *_targeter,
                                                       recordTargetErrors,
                                                       &childBatches );
            if ( !targetStatus.isOK() ) {
                // Don't do anything until a targeter refresh
                _targeter->noteCouldNotTarget();
                refreshedTargeter = true;
                ++_stats->numTargetErrors;
                dassert( childBatches.size() == 0u );
            }

            //
            // Send all child batches
            //

            size_t numSent = 0;
            size_t numToSend = childBatches.size();
            bool remoteMetadataChanging = false;
            while ( numSent != numToSend ) {

                // Collect batches out on the network, mapped by endpoint
                HostBatchMap pendingBatches;

                //
                // Send side
                //

                // Get as many batches as we can at once
                for ( vector<TargetedWriteBatch*>::iterator it = childBatches.begin();
                    it != childBatches.end(); ++it ) {

                    //
                    // Collect the info needed to dispatch our targeted batch
                    //

                    TargetedWriteBatch* nextBatch = *it;
                    // If the batch is NULL, we sent it previously, so skip
                    if ( nextBatch == NULL ) continue;

                    // Figure out what host we need to dispatch our targeted batch
                    ConnectionString shardHost;
                    Status resolveStatus = _resolver->chooseWriteHost( nextBatch->getEndpoint()
                                                                           .shardName,
                                                                       &shardHost );
                    if ( !resolveStatus.isOK() ) {

                        ++_stats->numResolveErrors;

                        // Record a resolve failure
                        // TODO: It may be necessary to refresh the cache if stale, or maybe just
                        // cancel and retarget the batch
                        WriteErrorDetail error;
                        buildErrorFrom( resolveStatus, &error );
                        batchOp.noteBatchError( *nextBatch, error );

                        // We're done with this batch
                        *it = NULL;
                        --numToSend;
                        continue;
                    }

                    // If we already have a batch for this host, wait until the next time
                    HostBatchMap::iterator pendingIt = pendingBatches.find( shardHost );
                    if ( pendingIt != pendingBatches.end() ) continue;

                    //
                    // We now have all the info needed to dispatch the batch
                    //

                    BatchedCommandRequest request( clientRequest.getBatchType() );
                    batchOp.buildBatchRequest( *nextBatch, &request );

                    // Internally we use full namespaces for request/response, but we send the
                    // command to a database with the collection name in the request.
                    NamespaceString nss( request.getNS() );
                    request.setNS( nss.coll() );

                    _dispatcher->addCommand( shardHost, nss.db(), request );

                    // Indicate we're done by setting the batch to NULL
                    // We'll only get duplicate hostEndpoints if we have broadcast and non-broadcast
                    // endpoints for the same host, so this should be pretty efficient without
                    // moving stuff around.
                    *it = NULL;

                    // Recv-side is responsible for cleaning up the nextBatch when used
                    pendingBatches.insert( make_pair( shardHost, nextBatch ) );
                }

                // Send them all out
                _dispatcher->sendAll();
                numSent += pendingBatches.size();

                //
                // Recv side
                //

                while ( _dispatcher->numPending() > 0 ) {

                    // Get the response
                    ConnectionString shardHost;
                    BatchedCommandResponse response;
                    Status dispatchStatus = _dispatcher->recvAny( &shardHost, &response );

                    // Get the TargetedWriteBatch to find where to put the response
                    dassert( pendingBatches.find( shardHost ) != pendingBatches.end() );
                    TargetedWriteBatch* batchRaw = pendingBatches.find( shardHost )->second;
                    scoped_ptr<TargetedWriteBatch> batch( batchRaw );

                    if ( dispatchStatus.isOK() ) {

                        TrackedErrors trackedErrors;
                        trackedErrors.startTracking( ErrorCodes::StaleShardVersion );

                        // Dispatch was ok, note response
                        batchOp.noteBatchResponse( *batch, response, &trackedErrors );

                        // Note if anything was stale
                        const vector<ShardError*>& staleErrors =
                            trackedErrors.getErrors( ErrorCodes::StaleShardVersion );

                        if ( staleErrors.size() > 0 ) {
                            noteStaleResponses( staleErrors, _targeter );
                            ++_stats->numStaleBatches;
                        }

                        // Remember if the shard is actively changing metadata right now
                        if ( isShardMetadataChanging( staleErrors ) ) {
                            remoteMetadataChanging = true;
                        }

                        // Remember that we successfully wrote to this shard
                        // NOTE: This will record lastOps for shards where we actually didn't update
                        // or delete any documents, which preserves old behavior but is conservative
                        _stats->noteWriteAt( shardHost,
                                             response.isLastOpSet() ? 
                                             response.getLastOp() : OpTime(),
                                             response.isElectionIdSet() ?
                                             response.getElectionId() : OID());
                    }
                    else {

                        // Error occurred dispatching, note it
                        WriteErrorDetail error;
                        buildErrorFrom( dispatchStatus, &error );
                        batchOp.noteBatchError( *batch, error );
                    }
                }
            }

            ++rounds;
            ++_stats->numRounds;

            // If we're done, get out
            if ( batchOp.isFinished() )
                break;

            // MORE WORK TO DO

            //
            // Refresh the targeter if we need to (no-op if nothing stale)
            //

            bool targeterChanged = false;
            Status refreshStatus = _targeter->refreshIfNeeded( &targeterChanged );

            if ( !refreshStatus.isOK() ) {

                // It's okay if we can't refresh, we'll just record errors for the ops if
                // needed.
                warning() << "could not refresh targeter" << causedBy( refreshStatus.reason() )
                          << endl;
            }

            //
            // Ensure progress is being made toward completing the batch op
            //

            int currCompletedOps = batchOp.numWriteOpsIn( WriteOpState_Completed );
            if ( currCompletedOps == numCompletedOps && !targeterChanged
                 && !remoteMetadataChanging ) {
                ++numRoundsWithoutProgress;
            }
            else {
                numRoundsWithoutProgress = 0;
            }
            numCompletedOps = currCompletedOps;

            if ( numRoundsWithoutProgress > kMaxRoundsWithoutProgress ) {

                stringstream msg;
                msg << "no progress was made executing batch write op in " << clientRequest.getNS()
                    << " after " << kMaxRoundsWithoutProgress << " rounds (" << numCompletedOps
                    << " ops completed in " << rounds << " rounds total)";

                WriteErrorDetail error;
                buildErrorFrom( Status( ErrorCodes::NoProgressMade, msg.str() ), &error );
                batchOp.setBatchError( error );
                break;
            }
        }

        batchOp.buildClientResponse( clientResponse );
    }
示例#16
0
void MediaControls::refreshCastButtonVisibility()
{
    refreshCastButtonVisibilityWithoutUpdate();
    BatchedControlUpdate batch(this);
}
示例#17
0
int main(void)
{
    GLFWwindow* window;


    int width = 1024;
    int height = 768;

    glfwSetErrorCallback (glfw_error_callback);
    if(!glfwInit ()) {
        fprintf (stderr, "ERROR: could not start GLFW3\n");
        return 1;
    }

	glfwWindowHint(GLFW_SAMPLES, 4);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
    glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    // to use this: http://stackoverflow.com/questions/17923782/simple-opengl-image-library-soil-uses-deprecated-functionality
//	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); 
	glfwWindowHint(GLFW_OPENGL_PROFILE,	GLFW_OPENGL_COMPAT_PROFILE);

    /*glfwWindowHint(GLFW_SAMPLES, 1); // 2x antialiasing
    int stencil_bits = 8;

    glfwWindowHint(GLFW_STENCIL_BITS, 8); // request a stencil buffer for object selection*/
    glfwWindowHint(GLFW_ALPHA_BITS, 8);
    
    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(width, height, "Game", NULL, NULL);
    glfwRestoreWindow(window);
    if (!window)
    {
        glfwTerminate();
        return -1; 
    }
    /* Make the window's context current */
    glfwMakeContextCurrent(window);
    
  
    // start GLEW extension handler
    glewExperimental = GL_TRUE;
    
    GLenum err = glewInit();
    if(err != GLEW_OK)
    {
        cout << "GLEW error: " << glewGetErrorString(err);
        exit(1); // or handle the error in a nicer way
    }
    GLenum glErr = glGetError();
    if (glErr != GL_NO_ERROR)
    {
        cout << "Caught GLEW init error in GL" << endl;
    }

    printOpenGLError();
            
    // get version info
    const GLubyte* gl_renderer = glGetString (GL_RENDERER); // get renderer string
    const GLubyte* gl_version = glGetString (GL_VERSION); // version as a string
    int gl_alpha;
    glGetIntegerv(GL_ALPHA_BITS, &gl_alpha);
    printf ("Renderer: %s\n", gl_renderer);
    printf ("OpenGL version supported %s\n", gl_version);
    printf ("Alphabits: %d", gl_alpha);
    
    glfwSwapInterval(1);
    
    printOpenGLError();
    cout << "Setting GL" << endl;
        
    //glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
    glClearColor(0.9f, 0.9f, 0.99f, 1.0f);
    glEnable(GL_DEPTH_TEST);
    glClearDepth(1.0f);
    glDepthFunc(GL_LESS);
	glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_CULL_FACE);

    glfwSetCharCallback(window, &Input::glfw_character_callback);
    glfwSetKeyCallback(window, &Input::glfw_key_callback);
    
    // create new Lua state
    lua_State *lua_state;
    lua_state = luaL_newstate();
    luaL_openlibs(lua_state);
 
    // load Lua libraries
    /*static const luaL_Reg lualibs[] =
    {
        { "base", luaopen_base },
        { "io", luaopen_io },
        { "string", luaopen_string },
        { NULL, NULL}
    };
 
    const luaL_Reg *lib = lualibs;
    for(; lib->func != NULL; lib++)
    {
        lib->func(lua_state);
        lua_settop(lua_state, 0);
    }*/
    
    lua_pushcfunction(lua_state, lua_set_camera);
    lua_setglobal(lua_state, "camera");
        
    lua_pushcfunction(lua_state, lua_drawcube);
    lua_setglobal(lua_state, "drawblock");
    
    lua_pushcfunction(lua_state, lua_load_renderer);
    lua_setglobal(lua_state, "load_renderer");
    
    lua_pushcfunction(lua_state, lua_drawbatch);
    lua_setglobal(lua_state, "drawbatch");
    
    lua_pushcfunction(lua_state, lua_time);
    lua_setglobal(lua_state, "time");
    
    run(lua_state, "class.lua");
    run(lua_state, "entity.lua");
    run(lua_state, "world.lua");
    run(lua_state, "component.lua");
    run(lua_state, "block.lua");
    run(lua_state, "physics.lua");
    run(lua_state, "load.lua");
    
    //camera = new CameraArcBall(glm::vec3(5,5,5), glm::vec3(0,0,0));
    
    //renderer.push_back(new RenderCube("assets/textures/grass.jpg", "assets/textures/dirt.jpg")); // default renderer?
        
    cout << "Starting main loop:" << endl;
    
    glm::vec3 size = glm::vec3(2);
    
    RenderQuad quad("assets/textures/jap.png", "inversion");
    RenderRect rect("assets/textures/tex16.png", "inversion2");
    
    BatchedRenderCube batch("assets/textures/dirt.jpg");
    
    cout << "[initmain]" << endl;
    printOpenGLError();
    
    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window) && !glfwGetKey(window, GLFW_KEY_ESCAPE))
    {
        glfwGetWindowSize(window, &width, &height);
        glViewport(0, 0, width, height);
        
        //glClearStencil(0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT /*| GL_STENCIL_BUFFER_BIT*/);
        
        // update input and actions
        Input::instance().update(window);
        
        // update view and projection
        camera->update(window);
        
        if(glfwGetKey(window, 'U'))
            run(lua_state, "action.lua");
        
        run(lua_state, "update.lua");
        run(lua_state, "render.lua");
        
        if(glfwGetKey(window, 'F'))
            std::cout << "FPS: " << calcFPS(glfwGetTime()) << std::endl;
        if(glfwGetKey(window, 'Q'))
            screenshot();
            
        quad.draw(camera, glm::vec3(0, 0, 0));
        
        if(glfwGetKey(window, GLFW_KEY_ENTER))
            rect.draw(camera, glm::vec2(width, height));
            
        printOpenGLError();
        
        /* Swap front and back buffers */
        glfwSwapBuffers(window);
        /* Poll for and process events */
        glfwPollEvents();
    }
	// Cleanup VBO and shader
	//glDeleteBuffers(1, &vertexbuffer);
	//glDeleteProgram(shader.id());
    
    // close the Lua state
    lua_close(lua_state);
    glfwTerminate();
    return 0;
}
示例#18
0
文件: tc.c 项目: hannes/iproute2
int main(int argc, char **argv)
{
	int ret;
	char *batch_file = NULL;

	while (argc > 1) {
		if (argv[1][0] != '-')
			break;
		if (matches(argv[1], "-stats") == 0 ||
			 matches(argv[1], "-statistics") == 0) {
			++show_stats;
		} else if (matches(argv[1], "-details") == 0) {
			++show_details;
		} else if (matches(argv[1], "-raw") == 0) {
			++show_raw;
		} else if (matches(argv[1], "-pretty") == 0) {
			++show_pretty;
		} else if (matches(argv[1], "-graph") == 0) {
			show_graph = 1;
		} else if (matches(argv[1], "-Version") == 0) {
			printf("tc utility, iproute2-ss%s\n", SNAPSHOT);
			return 0;
		} else if (matches(argv[1], "-iec") == 0) {
			++use_iec;
		} else if (matches(argv[1], "-help") == 0) {
			usage();
			return 0;
		} else if (matches(argv[1], "-force") == 0) {
			++force;
		} else if (matches(argv[1], "-batch") == 0) {
			argc--;	argv++;
			if (argc <= 1)
				usage();
			batch_file = argv[1];
		} else if (matches(argv[1], "-netns") == 0) {
			NEXT_ARG();
			if (netns_switch(argv[1]))
				return -1;
		} else if (matches(argv[1], "-names") == 0 ||
				matches(argv[1], "-nm") == 0) {
			use_names = true;
		} else if (matches(argv[1], "-cf") == 0 ||
				matches(argv[1], "-conf") == 0) {
			NEXT_ARG();
			conf_file = argv[1];
		} else if (matches(argv[1], "-timestamp") == 0) {
			timestamp++;
		} else if (matches(argv[1], "-tshort") == 0) {
			++timestamp;
			++timestamp_short;
		} else if (matches(argv[1], "-json") == 0) {
			++json;
		} else {
			fprintf(stderr, "Option \"%s\" is unknown, try \"tc -help\".\n", argv[1]);
			return -1;
		}
		argc--;	argv++;
	}

	if (batch_file)
		return batch(batch_file);

	if (argc <= 1) {
		usage();
		return 0;
	}

	tc_core_init();
	if (rtnl_open(&rth, 0) < 0) {
		fprintf(stderr, "Cannot open rtnetlink\n");
		exit(1);
	}

	if (use_names && cls_names_init(conf_file)) {
		ret = -1;
		goto Exit;
	}

	ret = do_cmd(argc-1, argv+1);
Exit:
	rtnl_close(&rth);

	if (use_names)
		cls_names_uninit();

	return ret;
}
示例#19
0
void MediaControls::refreshClosedCaptionsButtonVisibility()
{
    m_toggleClosedCaptionsButton->setIsWanted(mediaElement().hasClosedCaptions());
    BatchedControlUpdate batch(this);
}
示例#20
0
    void BatchWriteExec::executeBatch( const BatchedCommandRequest& clientRequest,
                                       BatchedCommandResponse* clientResponse ) {

        BatchWriteOp batchOp;
        batchOp.initClientRequest( &clientRequest );

        int numTargetErrors = 0;
        int numStaleBatches = 0;

        for ( int rounds = 0; !batchOp.isFinished(); rounds++ ) {

            //
            // Refresh the targeter if we need to (no-op if nothing stale)
            //

            Status refreshStatus = _targeter->refreshIfNeeded();

            if ( !refreshStatus.isOK() ) {

                // It's okay if we can't refresh, we'll just record errors for the ops if
                // needed.
                warning() << "could not refresh targeter" << causedBy( refreshStatus.reason() )
                          << endl;
            }

            //
            // Get child batches to send
            //

            vector<TargetedWriteBatch*> childBatches;

            //
            // Targeting errors can be caused by remote metadata changing (the collection could have
            // been dropped and recreated, for example with a new shard key).  If a remote metadata
            // change occurs *before* a client sends us a batch, we need to make sure that we don't
            // error out just because we're staler than the client - otherwise mongos will be have
            // unpredictable behavior.
            //
            // (If a metadata change happens *during* or *after* a client sends us a batch, however,
            // we make no guarantees about delivery.)
            //
            // For this reason, we don't record targeting errors until we've refreshed our targeting
            // metadata at least once *after* receiving the client batch - at that point, we know:
            //
            // 1) our new metadata is the same as the metadata when the client sent a batch, and so
            //    targeting errors are real.
            // OR
            // 2) our new metadata is a newer version than when the client sent a batch, and so
            //    the metadata must have changed after the client batch was sent.  We don't need to
            //    deliver in this case, since for all the client knows we may have gotten the batch
            //    exactly when the metadata changed.
            //
            // If we've had a targeting error or stale error, we've refreshed the metadata once and
            // can record target errors.
            bool recordTargetErrors = numTargetErrors > 0 || numStaleBatches > 0;

            Status targetStatus = batchOp.targetBatch( *_targeter,
                                                       recordTargetErrors,
                                                       &childBatches );
            if ( !targetStatus.isOK() ) {
                _targeter->noteCouldNotTarget();
                ++numTargetErrors;
                continue;
            }

            //
            // Send all child batches
            //

            size_t numSent = 0;
            while ( numSent != childBatches.size() ) {

                // Collect batches out on the network, mapped by endpoint
                EndpointBatchMap pendingBatches;

                //
                // Send side
                //

                // Get as many batches as we can at once
                for ( vector<TargetedWriteBatch*>::iterator it = childBatches.begin();
                    it != childBatches.end(); ++it ) {

                    TargetedWriteBatch* nextBatch = *it;
                    // If the batch is NULL, we sent it previously, so skip
                    if ( nextBatch == NULL ) continue;
                    const ConnectionString& hostEndpoint = nextBatch->getEndpoint().shardHost;

                    EndpointBatchMap::iterator pendingIt = pendingBatches.find( &hostEndpoint );

                    // If we already have a batch for this endpoint, continue
                    if ( pendingIt != pendingBatches.end() ) continue;

                    // Otherwise send it out to the endpoint via a command to a database

                    BatchedCommandRequest request( clientRequest.getBatchType() );
                    batchOp.buildBatchRequest( *nextBatch, &request );

                    // Internally we use full namespaces for request/response, but we send the
                    // command to a database with the collection name in the request.
                    NamespaceString nss( request.getNS() );
                    request.setNS( nss.coll() );

                    _dispatcher->addCommand( hostEndpoint, nss.db(), request );

                    // Indicate we're done by setting the batch to NULL
                    // We'll only get duplicate hostEndpoints if we have broadcast and non-broadcast
                    // endpoints for the same host, so this should be pretty efficient without
                    // moving stuff around.
                    *it = NULL;

                    // Recv-side is responsible for cleaning up the nextBatch when used
                    pendingBatches.insert( make_pair( &hostEndpoint, nextBatch ) );
                }

                // Send them all out
                _dispatcher->sendAll();
                numSent += pendingBatches.size();

                //
                // Recv side
                //

                while ( _dispatcher->numPending() > 0 ) {

                    // Get the response
                    ConnectionString endpoint;
                    BatchedCommandResponse response;
                    Status dispatchStatus = _dispatcher->recvAny( &endpoint, &response );

                    // Get the TargetedWriteBatch to find where to put the response
                    TargetedWriteBatch* batchRaw = pendingBatches.find( &endpoint )->second;
                    scoped_ptr<TargetedWriteBatch> batch( batchRaw );

                    if ( dispatchStatus.isOK() ) {

                        TrackedErrors trackedErrors;
                        trackedErrors.startTracking( ErrorCodes::StaleShardVersion );

                        // Dispatch was ok, note response
                        batchOp.noteBatchResponse( *batch, response, &trackedErrors );

                        // Note if anything was stale
                        const vector<ShardError*>& staleErrors =
                            trackedErrors.getErrors( ErrorCodes::StaleShardVersion );

                        if ( staleErrors.size() > 0 ) {
                            noteStaleResponses( staleErrors, _targeter );
                            ++numStaleBatches;
                        }
                    }
                    else {

                        // Error occurred dispatching, note it
                        BatchedErrorDetail error;
                        buildErrorFrom( dispatchStatus, &error );
                        batchOp.noteBatchError( *batch, error );
                    }
                }
            }
        }

        batchOp.buildClientResponse( clientResponse );
    }
示例#21
0
void SteamHelper::checkDepsAndStart()
{
#ifdef GAME_PLATFORM_MACOSX
  vfs::Path sdl2relpath = "Library/Frameworks/SDL2.framework";
  vfs::Path sdl2abspath = vfs::Directory::userDir()/sdl2relpath;

  if( !sdl2abspath.exist() )
  {
    vfs::Path tmp = "__install_frameworks.sh";
    Logger::warning( "Preparing updater for install frameworks " + tmp.toString() );

    std::ofstream batch(tmp.toCString());

    // grayman - accomodate spaces in pathnames
    tmp = vfs::Directory::applicationDir()/tmp;

    batch << "#!/usr/bin/env bash" << std::endl;
    batch << "SDLFR=~/Library/Frameworks/SDL2.framework" << std::endl;
    batch << "SAVEDIR=saves" << std::endl;
    batch << "LIBDIR=~/Library/Frameworks/" << std::endl;
    batch << "# if the file doesn't exist, try to create folder" << std::endl;
    batch << "if [ ! -d $SDLFR ]" << std::endl;
    batch << "then" << std::endl;
    batch << "hdiutil mount SDL2_mixer-2.0.0.dmg" << std::endl;
    batch << "hdiutil mount SDL2-2.0.3.dmg" << std::endl;
    batch << "mkdir -p $LIBDIR" << std::endl;
    batch << "cp -r /Volumes/SDL2/SDL2.framework $LIBDIR" << std::endl;
    batch << "cp -r /Volumes/SDL2_mixer/SDL2_mixer.framework $LIBDIR" << std::endl;
    batch << "hdiutil unmount /Volumes/SDL2" << std::endl;
    batch << "hdiutil unmount /Volumes/SDL2_mixer" << std::endl;
    batch << "fi" << std::endl;
    batch << "if [ ! -d $SAVEDIR ]" << std::endl;
    batch << "then" << std::endl;
    batch << "rm -f $SAVEDIR" << std::endl;
    batch << "mkdir $SAVEDIR" << std::endl;
    batch << "fi" << std::endl;

    batch.close();

    // Mark the shell script as executable in *nix
    OSystem::markFileAsExecutable(tmp.toCString());
    system( "./__install_frameworks.sh" );
  }

  system( "./caesaria.macos &" );
  exit(EXIT_SUCCESS);
#elif defined(GAME_PLATFORM_WIN)
  STARTUPINFOA siStartupInfo;
  PROCESS_INFORMATION piProcessInfo;

  memset(&siStartupInfo, 0, sizeof(siStartupInfo));
  memset(&piProcessInfo, 0, sizeof(piProcessInfo));

  siStartupInfo.cb = sizeof(siStartupInfo);

  vfs::Directory parentPath = vfs::Directory::applicationDir();

  Logger::warning( "Starting game in " + parentPath.toString() );

  BOOL success = CreateProcessA( NULL, "caesaria.exe", NULL, NULL,  false, 0, NULL,
                                 parentPath.toCString(), &siStartupInfo, &piProcessInfo);

#elif defined(GAME_PLATFORM_LINUX)
  system( "./caesaria.linux &" );
  exit(EXIT_SUCCESS);
#endif
}
示例#22
0
uint32 FolderWindow::onMessage(uint32 message, uint32 wParam, uint32 lParam)
{
    switch (message)
    {
    case WM_CONTEXTMENU:
    {
        POINT pt;
        GetCursorPos(&pt);

        int count = ListView_GetSelectedCount(list->getHandle());
        int item = ListView_GetNextItem(list->getHandle(), -1, LVNI_SELECTED);
        if (item >= 0)
        {
            int pos = list->getItemParam(item);
            while (count > 1 && item >= 0 && items[pos].type != ITEM_FOLDER &&
                    items[pos].type != ITEM_REPLAY)
            {
                item = ListView_GetNextItem(list->getHandle(), item, LVNI_SELECTED);
                pos = (item > 0 ? list->getItemParam(item) : -1);
            }

            EnableMenuItem(ctxMenu, ID_MENU_OPEN, count > 1 ? MF_GRAYED : MF_ENABLED);
            if (pos >= 0 && (items[pos].type == ITEM_FOLDER || items[pos].type == ITEM_REPLAY))
            {
                EnableMenuItem(ctxMenu, ID_MENU_BACKUP, MF_ENABLED);
                EnableMenuItem(ctxMenu, ID_MENU_COPY, MF_ENABLED);
                EnableMenuItem(ctxMenu, ID_MENU_DELETE, MF_ENABLED);
                EnableMenuItem(ctxMenu, ID_MENU_RENAME, count > 1 ? MF_GRAYED : MF_ENABLED);
            }
            else
            {
                EnableMenuItem(ctxMenu, ID_MENU_BACKUP, MF_GRAYED);
                EnableMenuItem(ctxMenu, ID_MENU_COPY, MF_GRAYED);
                EnableMenuItem(ctxMenu, ID_MENU_DELETE, MF_GRAYED);
                EnableMenuItem(ctxMenu, ID_MENU_RENAME, MF_GRAYED);
            }
        }
        else
        {
            EnableMenuItem(ctxMenu, ID_MENU_OPEN, MF_GRAYED);
            EnableMenuItem(ctxMenu, ID_MENU_BACKUP, MF_GRAYED);
            EnableMenuItem(ctxMenu, ID_MENU_COPY, MF_GRAYED);
            EnableMenuItem(ctxMenu, ID_MENU_DELETE, MF_GRAYED);
            EnableMenuItem(ctxMenu, ID_MENU_RENAME, MF_GRAYED);
        }
        ClipboardReader cbReader(CF_HDROP);
        EnableMenuItem(ctxMenu, ID_MENU_PASTE, cbReader.getData() ? MF_ENABLED : MF_GRAYED);

        int result = TrackPopupMenuEx(ctxMenu, TPM_HORIZONTAL | TPM_LEFTALIGN |
                                      TPM_RETURNCMD | TPM_NONOTIFY, pt.x, pt.y, list->getHandle(), NULL);

        switch (result)
        {
        case ID_MENU_OPEN:
        {
            NMITEMACTIVATE ia;
            memset(&ia, 0, sizeof ia);
            ia.hdr.code = LVN_ITEMACTIVATE;
            ia.hdr.hwndFrom = list->getHandle();
            ia.iItem = item;
            onMessage(WM_NOTIFY, 0, (uint32) &ia);
        }
        break;
        case ID_MENU_BACKUP:
        {
            BatchDialog batch(BatchDialog::mCopy);
            for (int item = ListView_GetNextItem(list->getHandle(), -1, LVNI_SELECTED);
                    item >= 0; item = ListView_GetNextItem(list->getHandle(), item, LVNI_SELECTED))
            {
                int pos = list->getItemParam(item);
                if (pos >= 0 && items[pos].type == ITEM_REPLAY)
                    batch.addReplay(items[pos].path);
                else if (pos >= 0 && items[pos].type == ITEM_FOLDER)
                    batch.addFolder(items[pos].path);
            }
            batch.run(list->getHandle());
        }
        break;
        case ID_MENU_COPY:
        case ID_MENU_PASTE:
        case ID_MENU_DELETE:
        case ID_MENU_RENAME:
        {
            NMLVKEYDOWN kd;
            memset(&kd, 0, sizeof kd);
            kd.hdr.code = LVN_KEYDOWN;
            kd.hdr.hwndFrom = list->getHandle();
            if (result == ID_MENU_COPY)
                kd.wVKey = 'C';
            else if (result == ID_MENU_PASTE)
                kd.wVKey = 'V';
            else if (result == ID_MENU_DELETE)
                kd.wVKey = VK_DELETE;
            else if (result == ID_MENU_RENAME)
                kd.wVKey = VK_F2;
            onMessage(WM_NOTIFY, VK_CONTROL, (uint32) &kd);
        }
        break;
        case ID_MENU_FOLDER:
        {
            String newdir = "New Folder";
            String fulldir = String::buildFullName(path, newdir);
            FileInfo fi;
            for (int num = 1; pathFileExists(fulldir); num++)
            {
                newdir = String::format("New Folder (%d)", num);
                fulldir = String::buildFullName(path, newdir);
            }
            if (CreateDirectory(fulldir, NULL))
            {
                int pos = list->addItem(newdir,
                                        getApp()->getImageLibrary()->getListIndex("IconClosedFolder"), items.length());
                ViewItem& item = items.push();
                item.path = fulldir;
                item.pos = pos;
                item.type = ITEM_FOLDER;
                ListView_EditLabel(list->getHandle(), pos);
            }
        }
        break;
        }
    }
    break;
    case WM_NOTIFY:
    {
        NMHDR* pnm = (NMHDR*) lParam;
        if (pnm->code == LVN_ITEMACTIVATE)
        {
            NMITEMACTIVATE* pia = (NMITEMACTIVATE*) pnm;
            int pos = -1;
            if (pia->iItem >= 0)
                pos = list->getItemParam(pia->iItem);
            if (pos >= 0 && pos < items.length())
            {
                if (items[pos].type == ITEM_UPFOLDER || items[pos].type == ITEM_FOLDER)
                    mainWnd->pushView(new FolderViewItem(items[pos].path));
                else if (items[pos].type == ITEM_REPLAY)
                    mainWnd->pushView(new ReplayViewItem(items[pos].path));
            }
        }
        else if (pnm->code == LVN_BEGINDRAG)
        {
            Array<String> sel;
            getSelList(sel);
            if (sel.length())
            {
                HGLOBAL data = CreateFileDrop(sel);
                if (data)
                {
                    selfDrag = true;
                    DoDragDrop(CF_HDROP, data, DROPEFFECT_MOVE | DROPEFFECT_COPY | DROPEFFECT_LINK);
                    selfDrag = false;
                }
            }
            return TRUE;
        }
        else if (pnm->code == LVN_BEGINLABELEDIT)
        {
            NMLVDISPINFO* di = (NMLVDISPINFO*) lParam;
            int pos = -1;
            if (di->item.iItem >= 0)
                pos = list->getItemParam(di->item.iItem);
            if (pos >= 0 && pos < items.length() &&
                    (items[pos].type == ITEM_FOLDER || items[pos].type == ITEM_REPLAY))
                return FALSE;
            return TRUE;
        }
        else if (pnm->code == LVN_ENDLABELEDIT)
        {
            NMLVDISPINFO* di = (NMLVDISPINFO*) lParam;
            int pos = -1;
            if (di->item.iItem >= 0)
                pos = list->getItemParam(di->item.iItem);
            if (di->item.pszText && pos >= 0 && pos < items.length() &&
                    (items[pos].type == ITEM_FOLDER || items[pos].type == ITEM_REPLAY))
            {
                String src = items[pos].path;
                String dst = String::buildFullName(String::getPath(src), di->item.pszText);
                src += '\0';
                if (items[pos].type == ITEM_REPLAY)
                    dst += ".w3g";
                dst += '\0';
                SHFILEOPSTRUCT op;
                memset(&op, 0, sizeof op);
                op.wFunc = FO_RENAME;
                op.pFrom = src;
                op.pTo = dst;
                if (SHFileOperationEx(&op) == 0)
                {
                    items[pos].path = String::buildFullName(String::getPath(items[pos].path), di->item.pszText);
                    if (items[pos].type == ITEM_REPLAY)
                        items[pos].path += ".w3g";
                    return TRUE;
                }
            }
            rebuild();
            return FALSE;
        }
        else if (pnm->code == LVN_COLUMNCLICK)
        {
            NMLISTVIEW* lv = (NMLISTVIEW*) lParam;
            bool colShow[colCount] = {true,
                                      cfg.selColumns & COL_SAVED,
                                      cfg.selColumns & COL_SIZE,
                                      cfg.selColumns & COL_NAME,
                                      cfg.selColumns & COL_RATIO,
                                      cfg.selColumns & COL_LENGTH,
                                      cfg.selColumns & COL_MODE
                                     };
            int col = lv->iSubItem;
            for (int i = 0; i < col && col < colCount - 1; i++)
                if (!colShow[i])
                    col++;
            int pos = 0;
            while (pos < colCount - 1 && cfg.colSort[pos] != col && cfg.colSort[pos] != ~col)
                pos++;
            if (pos == 0)
                cfg.colSort[0] = ~cfg.colSort[0];
            else
            {
                for (int i = pos; i > 0; i--)
                    cfg.colSort[i] = cfg.colSort[i - 1];
                cfg.colSort[0] = col;
            }
            rebuild();
        }
        else if (pnm->code == HDN_ENDDRAG)
            PostMessage(list->getHandle(), WM_POSTHEADERDRAG, 0, 0);
        else if (pnm->code == HDN_ENDTRACK)
        {
            NMHEADER* nhdr = (NMHEADER*) pnm;
            bool colShow[colCount] = {true,
                                      cfg.selColumns & COL_SAVED,
                                      cfg.selColumns & COL_SIZE,
                                      cfg.selColumns & COL_NAME,
                                      cfg.selColumns & COL_RATIO,
                                      cfg.selColumns & COL_LENGTH,
                                      cfg.selColumns & COL_MODE
                                     };
            int count = 0;
            int colUnpos[colCount];
            for (int i = 0; i < colCount; i++)
                if (colShow[i])
                    colUnpos[count++] = i;
            if (nhdr->iItem >= 0 && nhdr->iItem < count &&
                    nhdr->pitem && nhdr->pitem->mask & HDI_WIDTH)
            {
                int col = colUnpos[nhdr->iItem];
                cfg.colWidth[col] = nhdr->pitem->cxy;
            }
        }
        else if (pnm->code == LVN_KEYDOWN)
        {
            NMLVKEYDOWN* kd = (NMLVKEYDOWN*) lParam;
            bool controlKey = ((GetAsyncKeyState(VK_CONTROL) & 0x8000) || wParam == VK_CONTROL);
            if (kd->wVKey == 'C' && controlKey)
            {
                Array<String> sel;
                getSelList(sel);
                if (sel.length())
                {
                    HGLOBAL hDrop = CreateFileDrop(sel);
                    SetClipboard(CF_HDROP, hDrop);
                }
            }
            else if (kd->wVKey == 'V' && controlKey)
            {
                ClipboardReader clip(CF_HDROP);
                HGLOBAL hDrop = clip.getData();
                if (hDrop)
                    doPaste(hDrop, DROPEFFECT_COPY, path);
            }
            else if (kd->wVKey == VK_DELETE)
            {
                Array<String> sel;
                getSelList(sel);
                if (sel.length())
                {
                    char* str = FileListToString(sel);
                    SHFILEOPSTRUCT fileop;
                    memset(&fileop, 0, sizeof fileop);
                    fileop.wFunc = FO_DELETE;
                    fileop.pFrom = str;
                    SHFileOperationEx(&fileop);
                }
            }
            else if (kd->wVKey == VK_F2)
            {
                SetFocus(list->getHandle());
                int sel = ListView_GetNextItem(list->getHandle(), -1, LVNI_FOCUSED);
                if (sel < 0)
                    sel = 0;
                ListView_EditLabel(list->getHandle(), sel);
            }
        }
    }
    break;
    case WM_DRAGOVER:
    case WM_DRAGLEAVE:
    {
        LVHITTESTINFO ht;
        LVITEM lvi;
        memset(&lvi, 0, sizeof lvi);
        if (message == WM_DRAGOVER)
        {
            ht.pt.x = LOWORD(lParam);
            ht.pt.y = HIWORD(lParam);
            ListView_HitTest(list->getHandle(), &ht);
            if (ht.iItem >= 0)
            {
                lvi.iItem = ht.iItem;
                lvi.mask = LVIF_PARAM | LVIF_STATE;
                lvi.stateMask = LVIS_SELECTED;
                ListView_GetItem(list->getHandle(), &lvi);
                if (lvi.lParam < 0 || lvi.lParam >= items.length() ||
                        (items[lvi.lParam].type != ITEM_UPFOLDER && items[lvi.lParam].type != ITEM_FOLDER))
                    ht.iItem = -1;
                if (selfDrag && (lvi.state & LVIS_SELECTED))
                    ht.iItem = -1;
            }
            if (wParam && selfDrag && ht.iItem == -1 && *(DWORD*) wParam == DROPEFFECT_MOVE)
                *(DWORD*) wParam = DROPEFFECT_NONE;
        }
        else
            ht.iItem = -1;
        if (ht.iItem != list->highlight)
        {
            lvi.mask = LVIF_STATE;
            lvi.stateMask = LVIS_DROPHILITED;
            if (list->highlight >= 0)
            {
                lvi.iItem = list->highlight;
                ListView_SetItem(list->getHandle(), &lvi);
            }
            if (ht.iItem >= 0)
            {
                lvi.state = LVIS_DROPHILITED;
                lvi.iItem = ht.iItem;
                ListView_SetItem(list->getHandle(), &lvi);
            }
            list->highlight = ht.iItem;
        }
    }
    break;
    case WM_DRAGDROP:
        if (lParam == DROPEFFECT_MOVE || lParam == DROPEFFECT_COPY)
        {
            String opTo = path;
            if (list->highlight >= 0)
            {
                int param = list->getItemParam(list->highlight);
                if (param >= 0 && param < items.length() &&
                        (items[param].type == ITEM_UPFOLDER || items[param].type == ITEM_FOLDER))
                    opTo = items[param].path;
            }
            doPaste((HGLOBAL) wParam, lParam, opTo);
        }
        return 0;
    case WM_POSTHEADERDRAG:
    {
        bool colShow[colCount] = {true,
                                  cfg.selColumns & COL_SAVED,
                                  cfg.selColumns & COL_SIZE,
                                  cfg.selColumns & COL_NAME,
                                  cfg.selColumns & COL_RATIO,
                                  cfg.selColumns & COL_LENGTH,
                                  cfg.selColumns & COL_MODE
                                 };
        int count = 0;
        int colUnpos[colCount];
        for (int i = 0; i < colCount; i++)
            if (colShow[i])
                colUnpos[count++] = i;
        int colOrder[colCount];
        ListView_GetColumnOrderArray(list->getHandle(), count, colOrder);
        int pos = 0;
        for (int i = 0; i < colCount; i++)
            if (colShow[cfg.colOrder[i]])
                cfg.colOrder[i] = colUnpos[colOrder[pos++]];
    }
    break;
    case WM_REBUILDLIST:
        if (ListView_GetEditControl(list->getHandle()) == NULL)
            rebuild();
        break;
    case WM_UPDATELISTITEM:
        updateListItem(wParam, lParam);
        break;
    default:
        return M_UNHANDLED;
    }
    return 0;
}
示例#23
0
int main(int argc, char **argv)
{
	char *basename;

	basename = strrchr(argv[0], '/');
	if (basename == NULL)
		basename = argv[0];
	else
		basename++;

	while (argc > 1) {
		char *opt = argv[1];
		if (strcmp(opt,"--") == 0) {
			argc--; argv++;
			break;
		}
		if (opt[0] != '-')
			break;
		if (opt[1] == '-')
			opt++;
		if (matches(opt, "-family") == 0) {
			argc--;
			argv++;
			if (argc <= 1)
				usage();
			if (strcmp(argv[1], "inet") == 0)
				preferred_family = AF_INET;
			else if (strcmp(argv[1], "inet6") == 0)
				preferred_family = AF_INET6;
			else if (strcmp(argv[1], "dnet") == 0)
				preferred_family = AF_DECnet;
			else if (strcmp(argv[1], "link") == 0)
				preferred_family = AF_PACKET;
			else if (strcmp(argv[1], "ipx") == 0)
				preferred_family = AF_IPX;
			else if (strcmp(argv[1], "help") == 0)
				usage();
			else
				invarg(argv[1], "invalid protocol family");
		} else if (strcmp(opt, "-4") == 0) {
			preferred_family = AF_INET;
		} else if (strcmp(opt, "-6") == 0) {
			preferred_family = AF_INET6;
		} else if (strcmp(opt, "-0") == 0) {
			preferred_family = AF_PACKET;
		} else if (strcmp(opt, "-I") == 0) {
			preferred_family = AF_IPX;
		} else if (strcmp(opt, "-D") == 0) {
			preferred_family = AF_DECnet;
		} else if (matches(opt, "-stats") == 0 ||
			   matches(opt, "-statistics") == 0) {
			++show_stats;
		} else if (matches(opt, "-details") == 0) {
			++show_details;
		} else if (matches(opt, "-resolve") == 0) {
			++resolve_hosts;
		} else if (matches(opt, "-oneline") == 0) {
			++oneline;
		} else if (matches(opt, "-timestamp") == 0) {
			++timestamp;
#if 0
		} else if (matches(opt, "-numeric") == 0) {
			rtnl_names_numeric++;
#endif
		} else if (matches(opt, "-Version") == 0) {
			printf("ip utility, iproute2-ss%s\n", SNAPSHOT);
			exit(0);
#ifndef ANDROID
		} else if (matches(opt, "-force") == 0) {
			++force;
		} else if (matches(opt, "-batch") == 0) {
			argc--;
			argv++;
			if (argc <= 1)
				usage();
			batch_file = argv[1];
#endif
		} else if (matches(opt, "-rcvbuf") == 0) {
			unsigned int size;

			argc--;
			argv++;
			if (argc <= 1)
				usage();
			if (get_unsigned(&size, argv[1], 0)) {
				fprintf(stderr, "Invalid rcvbuf size '%s'\n",
					argv[1]);
				exit(-1);
			}
			rcvbuf = size;
		} else if (matches(opt, "-help") == 0) {
			usage();
		} else {
			fprintf(stderr, "Option \"%s\" is unknown, try \"ip -help\".\n", opt);
			exit(-1);
		}
		argc--;	argv++;
	}

	_SL_ = oneline ? "\\" : "\n" ;

#ifndef ANDROID
	if (batch_file)
		return batch(batch_file);
#endif

	if (rtnl_open(&rth, 0) < 0)
		exit(1);

	if (strlen(basename) > 2)
		return do_cmd(basename+2, argc, argv);

	if (argc > 1)
		return do_cmd(argv[1], argc-1, argv+1);

	rtnl_close(&rth);
	usage();
}
示例#24
0
文件: command.c 项目: TijmenW/FreeDOS
static void execute(char *first, char *rest)
{
  /*
   * This command (in first) was not found in the command table
   *
   *
   * first - first word on command line
   * rest  - rest of command line
   *
   */

  char *fullname;

  assert(first);
  assert(rest);

  /* check for a drive change */
  if ((strcmp(first + 1, ":") == 0) && isalpha(*first))
  {
  	changeDrive(*first);
    return;
  }

  if (strchr(first,'?') || strchr(first,'*'))
  {
    error_bad_command();
    return;
  }

  /* search through %PATH% for the binary */
  errno = 0;
  fullname = find_which(first);
  dprintf(("[find_which(%s) returned %s]\n", first, fullname));

  if (!fullname)
  {
    error_bad_command();
    return;
  }

  /* check if this is a .BAT file */
  assert(strrchr(fullname, '.'));

  if (stricmp(strrchr(fullname, '.'), ".bat") == 0)
  {
    dprintf(("[BATCH: %s %s]\n", fullname, rest));
    batch(fullname, first, rest);
  }
  else
    /* exec the program */
  {
    int result;

    dprintf(("[EXEC: %s %s]\n", fullname, rest));

	if (strlen(rest) > MAX_EXTERNAL_COMMAND_SIZE)
	{
		error_line_too_long();
		return;
	}

/* Prepare to call an external program */

	/* Unload the message block if not loaded persistently */
	if(!persistentMSGs)
		unloadMsgs();

/* Execute the external program */
#ifdef FEATURE_KERNEL_SWAP_SHELL
    if(swapOnExec == TRUE
	 && kswapMkStruc(fullname, rest)) {
	 	/* The Criter and ^Break handlers has been installed within
	 		the PSP in kswapRegister() --> nothing to do here */
	 	dprintf(("[EXEC: exiting to kernel swap support]\n"));
	 	exit(123);		/* Let the kernel swap support do the rest */
	}
#ifdef DEBUG
	if(swapOnExec == TRUE)
		dprintf(("KSWAP: failed to save context, proceed without swapping\n"));
#endif
#endif
		/* Install the dummy (always abort) handler */
	setvect(0x23, (void interrupt(*)()) kswapContext->cbreak_hdlr);
    result = exec(fullname, rest, 0);
	setvect(0x23, cbreak_handler);		/* Install local CBreak handler */

    perform_exec_result(result);
  }
}
示例#25
0
文件: Text.cpp 项目: rokups/Urho3D
void Text::GetBatches(ea::vector<UIBatch>& batches, ea::vector<float>& vertexData, const IntRect& currentScissor)
{
    FontFace* face = font_ ? font_->GetFace(fontSize_) : nullptr;
    if (!face)
    {
        hovering_ = false;
        return;
    }

    // If face has changed or char locations are not valid anymore, update before rendering
    if (charLocationsDirty_ || !fontFace_ || face != fontFace_)
        UpdateCharLocations();
    // If face uses mutable glyphs mechanism, reacquire glyphs before rendering to make sure they are in the texture
    else if (face->HasMutableGlyphs())
    {
        for (unsigned i = 0; i < printText_.size(); ++i)
            face->GetGlyph(printText_[i]);
    }

    // Hovering and/or whole selection batch
    UISelectable::GetBatches(batches, vertexData, currentScissor);

    // Partial selection batch
    if (!selected_ && selectionLength_ && charLocations_.size() >= selectionStart_ + selectionLength_ && selectionColor_.a_ > 0.0f)
    {
        UIBatch batch(this, BLEND_ALPHA, currentScissor, nullptr, &vertexData);
        batch.SetColor(selectionColor_);

        Vector2 currentStart = charLocations_[selectionStart_].position_;
        Vector2 currentEnd = currentStart;
        for (unsigned i = selectionStart_; i < selectionStart_ + selectionLength_; ++i)
        {
            // Check if row changes, and start a new quad in that case
            if (charLocations_[i].size_ != Vector2::ZERO)
            {
                if (charLocations_[i].position_.y_ != currentStart.y_)
                {
                    batch.AddQuad(currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_,
                        currentEnd.y_ - currentStart.y_, 0, 0);
                    currentStart = charLocations_[i].position_;
                    currentEnd = currentStart + charLocations_[i].size_;
                }
                else
                {
                    currentEnd.x_ += charLocations_[i].size_.x_;
                    currentEnd.y_ = Max(currentStart.y_ + charLocations_[i].size_.y_, currentEnd.y_);
                }
            }
        }
        if (currentEnd != currentStart)
        {
            batch.AddQuad(currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_, currentEnd.y_ - currentStart.y_, 0, 0);
        }

        UIBatch::AddOrMerge(batch, batches);
    }

    // Text batch
    TextEffect textEffect = font_->IsSDFFont() ? TE_NONE : textEffect_;
    const ea::vector<ea::shared_ptr<Texture2D> >& textures = face->GetTextures();
    for (unsigned n = 0; n < textures.size() && n < pageGlyphLocations_.size(); ++n)
    {
        // One batch per texture/page
        UIBatch pageBatch(this, BLEND_ALPHA, currentScissor, textures[n], &vertexData);

        const ea::vector<GlyphLocation>& pageGlyphLocation = pageGlyphLocations_[n];

        switch (textEffect)
        {
        case TE_NONE:
            ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
            break;

        case TE_SHADOW:
            ConstructBatch(pageBatch, pageGlyphLocation, shadowOffset_.x_, shadowOffset_.y_, &effectColor_, effectDepthBias_);
            ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
            break;

        case TE_STROKE:
            if (roundStroke_)
            {
                // Samples should be even or glyph may be redrawn in wrong x y pos making stroke corners rough
                // Adding to thickness helps with thickness of 1 not having enought samples for this formula
                // or certain fonts with reflex corners requiring more glyph samples for a smooth stroke when large
                int thickness = Min(strokeThickness_, fontSize_);
                int samples = thickness * thickness + (thickness % 2 == 0 ? 4 : 3);
                float angle = 360.f / samples;
                auto floatThickness = (float)thickness;
                for (int i = 0; i < samples; ++i)
                {
                    float x = Cos(angle * i) * floatThickness;
                    float y = Sin(angle * i) * floatThickness;
                    ConstructBatch(pageBatch, pageGlyphLocation, x, y, &effectColor_, effectDepthBias_);
                }
            }
            else
            {
                int thickness = Min(strokeThickness_, fontSize_);
                int x, y;
                for (x = -thickness; x <= thickness; ++x)
                {
                    for (y = -thickness; y <= thickness; ++y)
                    {
                        // Don't draw glyphs that aren't on the edges
                        if (x > -thickness && x < thickness &&
                            y > -thickness && y < thickness)
                            continue;

                        ConstructBatch(pageBatch, pageGlyphLocation, x, y, &effectColor_, effectDepthBias_);
                    }
                }
            }
            ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
            break;
        }

        UIBatch::AddOrMerge(pageBatch, batches);
    }
}
示例#26
0
void MediaControls::onTextTracksAddedOrRemoved() {
  m_toggleClosedCaptionsButton->setIsWanted(mediaElement().hasClosedCaptions());
  BatchedControlUpdate batch(this);
}
示例#27
0
bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
    CDBBatch batch(*this);
    for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
        batch.Write(std::make_pair(DB_TXINDEX, it->first), it->second);
    return WriteBatch(batch);
}
示例#28
0
void
Scheduler::run()
{
    t_scheduler = this;
    if (gettid() != m_rootThread) {
        // Running in own thread
        t_fiber = Fiber::getThis().get();
    } else {
        // Hijacked a thread
        MORDOR_ASSERT(t_fiber.get() == Fiber::getThis().get());
    }
    Fiber::ptr idleFiber(new Fiber(boost::bind(&Scheduler::idle, this)));
    MORDOR_LOG_VERBOSE(g_log) << this << " starting thread with idle fiber " << idleFiber;
    Fiber::ptr dgFiber;
    // use a vector for O(1) .size()
    std::vector<FiberAndThread> batch(m_batchSize);
    bool isActive = false;
    while (true) {
        batch.clear();
        bool dontIdle = false;
        bool tickleMe = false;
        {
            boost::mutex::scoped_lock lock(m_mutex);
            // Kill ourselves off if needed
            if (m_threads.size() > m_threadCount && gettid() != m_rootThread) {
                // Accounting
                if (isActive)
                    --m_activeThreadCount;
                // Kill off the idle fiber
                try {
                    throw boost::enable_current_exception(
                        OperationAbortedException());
                } catch(...) {
                    idleFiber->inject(boost::current_exception());
                }
                // Detach our thread
                for (std::vector<boost::shared_ptr<Thread> >
                    ::iterator it = m_threads.begin();
                    it != m_threads.end();
                    ++it)
                    if ((*it)->tid() == gettid()) {
                        m_threads.erase(it);
                        if (m_threads.size() > m_threadCount)
                            tickle();
                        return;
                    }
                MORDOR_NOTREACHED();
            }

            std::list<FiberAndThread>::iterator it(m_fibers.begin());
            while (it != m_fibers.end()) {
                // If we've met our batch size, and we're not checking to see
                // if we need to tickle another thread, then break
                if ( (tickleMe || m_activeThreadCount == threadCount()) &&
                    batch.size() == m_batchSize)
                    break;

                if (it->thread != emptytid() && it->thread != gettid()) {
                    MORDOR_LOG_DEBUG(g_log) << this
                        << " skipping item scheduled for thread "
                        << it->thread;

                    // Wake up another thread to hopefully service this
                    tickleMe = true;
                    dontIdle = true;
                    ++it;
                    continue;
                }
                MORDOR_ASSERT(it->fiber || it->dg);
                // This fiber is still executing; probably just some race
                // race condition that it needs to yield on one thread
                // before running on another thread
                if (it->fiber && it->fiber->state() == Fiber::EXEC) {
                    MORDOR_LOG_DEBUG(g_log) << this
                        << " skipping executing fiber " << it->fiber;
                    ++it;
                    dontIdle = true;
                    continue;
                }
                // We were just checking if there is more work; there is, so
                // set the flag and don't actually take this piece of work
                if (batch.size() == m_batchSize) {
                    tickleMe = true;
                    break;
                }
                batch.push_back(*it);
                it = m_fibers.erase(it);
                if (!isActive) {
                    ++m_activeThreadCount;
                    isActive = true;
                }
            }
            if (batch.empty() && isActive) {
                --m_activeThreadCount;
                isActive = false;
            }
        }
        if (tickleMe)
            tickle();
        MORDOR_LOG_DEBUG(g_log) << this
            << " got " << batch.size() << " fiber/dgs to process (max: "
            << m_batchSize << ", active: " << isActive << ")";
        MORDOR_ASSERT(isActive == !batch.empty());
        if (!batch.empty()) {
            std::vector<FiberAndThread>::iterator it;
            for (it = batch.begin(); it != batch.end(); ++it) {
                Fiber::ptr f = it->fiber;
                boost::function<void ()> dg = it->dg;

                try {
                    if (f && f->state() != Fiber::TERM) {
                        MORDOR_LOG_DEBUG(g_log) << this << " running " << f;
                        f->yieldTo();
                    } else if (dg) {
                        if (!dgFiber)
                            dgFiber.reset(new Fiber(dg));
                        dgFiber->reset(dg);
                        MORDOR_LOG_DEBUG(g_log) << this << " running " << dg;
                        dgFiber->yieldTo();
                        if (dgFiber->state() != Fiber::TERM)
                            dgFiber.reset();
                        else
                            dgFiber->reset(NULL);
                    }
                } catch (...) {
                    MORDOR_LOG_FATAL(Log::root())
                        << boost::current_exception_diagnostic_information();
                    throw;
                }
            }
            continue;
        }
        if (dontIdle)
            continue;

        if (idleFiber->state() == Fiber::TERM) {
            MORDOR_LOG_DEBUG(g_log) << this << " idle fiber terminated";
            if (gettid() == m_rootThread)
                m_callingFiber.reset();
            // Unblock the next thread
            if (threadCount() > 1)
                tickle();
            return;
        }
        MORDOR_LOG_DEBUG(g_log) << this << " idling";
        idleFiber->call();
    }
}
示例#29
0
文件: ip.c 项目: Distrotech/iproute2
int main(int argc, char **argv)
{
	char *basename;
	char *batch_file = NULL;

	basename = strrchr(argv[0], '/');
	if (basename == NULL)
		basename = argv[0];
	else
		basename++;

	while (argc > 1) {
		char *opt = argv[1];
		if (strcmp(opt,"--") == 0) {
			argc--; argv++;
			break;
		}
		if (opt[0] != '-')
			break;
		if (opt[1] == '-')
			opt++;
		if (matches(opt, "-loops") == 0) {
			argc--;
			argv++;
			if (argc <= 1)
				usage();
                        max_flush_loops = atoi(argv[1]);
                } else if (matches(opt, "-family") == 0) {
			argc--;
			argv++;
			if (argc <= 1)
				usage();
			if (strcmp(argv[1], "help") == 0)
				usage();
			else
				preferred_family = read_family(argv[1]);
			if (preferred_family == AF_UNSPEC)
				invarg("invalid protocol family", argv[1]);
		} else if (strcmp(opt, "-4") == 0) {
			preferred_family = AF_INET;
		} else if (strcmp(opt, "-6") == 0) {
			preferred_family = AF_INET6;
		} else if (strcmp(opt, "-0") == 0) {
			preferred_family = AF_PACKET;
		} else if (strcmp(opt, "-I") == 0) {
			preferred_family = AF_IPX;
		} else if (strcmp(opt, "-D") == 0) {
			preferred_family = AF_DECnet;
		} else if (strcmp(opt, "-M") == 0) {
			preferred_family = AF_MPLS;
		} else if (strcmp(opt, "-B") == 0) {
			preferred_family = AF_BRIDGE;
		} else if (matches(opt, "-human") == 0 ||
			   matches(opt, "-human-readable") == 0) {
			++human_readable;
		} else if (matches(opt, "-iec") == 0) {
			++use_iec;
		} else if (matches(opt, "-stats") == 0 ||
			   matches(opt, "-statistics") == 0) {
			++show_stats;
		} else if (matches(opt, "-details") == 0) {
			++show_details;
		} else if (matches(opt, "-resolve") == 0) {
			++resolve_hosts;
		} else if (matches(opt, "-oneline") == 0) {
			++oneline;
		} else if (matches(opt, "-timestamp") == 0) {
			++timestamp;
		} else if (matches(opt, "-tshort") == 0) {
			++timestamp;
			++timestamp_short;
#if 0
		} else if (matches(opt, "-numeric") == 0) {
			rtnl_names_numeric++;
#endif
		} else if (matches(opt, "-Version") == 0) {
			printf("ip utility, iproute2-ss%s\n", SNAPSHOT);
			exit(0);
		} else if (matches(opt, "-force") == 0) {
			++force;
		} else if (matches(opt, "-batch") == 0) {
			argc--;
			argv++;
			if (argc <= 1)
				usage();
			batch_file = argv[1];
		} else if (matches(opt, "-rcvbuf") == 0) {
			unsigned int size;

			argc--;
			argv++;
			if (argc <= 1)
				usage();
			if (get_unsigned(&size, argv[1], 0)) {
				fprintf(stderr, "Invalid rcvbuf size '%s'\n",
					argv[1]);
				exit(-1);
			}
			rcvbuf = size;
		} else if (matches(opt, "-color") == 0) {
			enable_color();
		} else if (matches(opt, "-help") == 0) {
			usage();
		} else if (matches(opt, "-netns") == 0) {
			NEXT_ARG();
			if (netns_switch(argv[1]))
				exit(-1);
		} else if (matches(opt, "-all") == 0) {
			do_all = true;
		} else {
			fprintf(stderr, "Option \"%s\" is unknown, try \"ip -help\".\n", opt);
			exit(-1);
		}
		argc--;	argv++;
	}

	_SL_ = oneline ? "\\" : "\n" ;

	if (batch_file)
		return batch(batch_file);

	if (rtnl_open(&rth, 0) < 0)
		exit(1);

	if (strlen(basename) > 2)
		return do_cmd(basename+2, argc, argv);

	if (argc > 1)
		return do_cmd(argv[1], argc-1, argv+1);

	rtnl_close(&rth);
	usage();
}
int process_args(int argc, char *argv[], char batch_mode)
{
	int c;
	char mode = 0;
	char time_ok = 0;
	char room = 0;
	char *filename;
	record *rec = calloc(1, sizeof(record));
	record *first = NULL;
	record *last = NULL;
	EVP_CIPHER_CTX en_ctx, de_ctx;

	optind = 0;
	opterr = 0;
	while ((c = getopt(argc, argv, ":T:K:E:G:ALR:B:")) != -1)
		switch (c)
		{
		case 'T':
			if (mode == BATCH_MODE) 
				return print_error(ARG_ERROR);
			mode = DEFAULT_MODE;
			if (strtoi(optarg, &(rec->timestamp)) || !rec->timestamp)
				return print_error(ARG_ERROR);
			time_ok = 1;
			break;
		case 'K':
			if (mode == BATCH_MODE)
				return print_error(ARG_ERROR);
			mode = DEFAULT_MODE;
			if (!is_token_valid(optarg))
				return print_error(ARG_ERROR);
			rec->token = optarg;
			break;
		case 'E':
			if (mode == BATCH_MODE)
				return print_error(ARG_ERROR);
			mode = DEFAULT_MODE;
			if (rec->ptype == GUEST)
				return print_error(ARG_ERROR);
			rec->ptype = EMPLOYEE;
			if (!is_name_valid(optarg))
				return print_error(ARG_ERROR);
			rec->name = optarg;
			break;
		case 'G':
			if (mode == BATCH_MODE)
				return print_error(ARG_ERROR);
			mode = DEFAULT_MODE;
			if (rec->ptype == EMPLOYEE)
				return print_error(ARG_ERROR);
			rec->ptype = GUEST;
			if (!is_name_valid(optarg))
				return print_error(ARG_ERROR);
			rec->name = optarg;
			break;
		case 'A':
			if (mode == BATCH_MODE)
				return print_error(ARG_ERROR);
			mode = DEFAULT_MODE;
			if (rec->etype == DEPARTURE)
				return print_error(ARG_ERROR);
			rec->etype = ARRIVAL;
			break;
		case 'L':
			if (mode == BATCH_MODE)
				return print_error(ARG_ERROR);
			mode = DEFAULT_MODE;
			if (rec->etype == ARRIVAL)
				return print_error(ARG_ERROR);
			rec->etype = DEPARTURE;
			break;
		case 'R':
			if (mode == BATCH_MODE)
				return print_error(ARG_ERROR);
			mode = DEFAULT_MODE;
			if (strtoi(optarg, &(rec->room_id)))
				return print_error(ARG_ERROR);
			room = 1;
			break;
		case 'B':
			if (mode == DEFAULT_MODE || batch_mode)
				return print_error(ARG_ERROR);
			mode = BATCH_MODE;
			filename = optarg;
			break;
		default:
			return print_error(ARG_ERROR);
		}
	
	if (mode == BATCH_MODE)
	{
		free(rec);
		if (batch(filename))
			return print_error(ARG_ERROR);
		return NO_ERROR;
	}

	//Checa opcoes mandatorias
	if (mode != DEFAULT_MODE || !time_ok || rec->token == NULL || rec->name == NULL 
	  || rec->etype == UNDEF_E || optind >= argc)
		return print_error(ARG_ERROR);

	//Ajusta o evento de acordo com a presenca de sala
	if (!room)
	{
		if (rec->etype == ARRIVAL)
			rec->etype = G_ARRIVAL;
		else
			rec->etype = G_DEPARTURE;
	}

	//Inicia contextos de seguranca
	if ((aes_init((unsigned char *) rec->token, strlen(rec->token), &en_ctx, &de_ctx)))
		return print_error(ARG_ERROR);

	//validacoes de consistencia
	c = read_records(&first, argv[optind], &last, &de_ctx);
	if (c)
	{
		EVP_CIPHER_CTX_cleanup(&en_ctx);
		EVP_CIPHER_CTX_cleanup(&de_ctx);
		return c;
	}

	if ((c = check_record(first, rec)))
	{
		del_records(&first);
		free(rec);
		EVP_CIPHER_CTX_cleanup(&en_ctx);
		EVP_CIPHER_CTX_cleanup(&de_ctx);
		return print_error(ARG_ERROR);
	}

	if (!first)
		first = rec;
	else
	{
		if (!last)
			last = first;
		last->next = rec;
	}
	write_record(first, argv[optind], &en_ctx);

	//TODO em batch, esses registros poderiam ser mantidos para evitar reler o arquivo.
	if (first != rec)
	{
		last->next = NULL;
		del_records(&first);
	}

	free(rec);
	EVP_CIPHER_CTX_cleanup(&en_ctx);
	EVP_CIPHER_CTX_cleanup(&de_ctx);

	return NO_ERROR;
}