Ejemplo n.º 1
0
JobInterface::JobInterface( Job* job )
:
    QObject( job ),
    m_job( job ),
    m_lastProgress( 0 ),
    m_lastSubProgress( 0 )
{
    if( m_job ) {
        connect( m_job, SIGNAL(newTask(QString)), this, SIGNAL(newTask(QString)) );
        connect( m_job, SIGNAL(newSubTask(QString)), this, SIGNAL(newSubTask(QString)) );
        connect( m_job, SIGNAL(infoMessage(QString,int)), this, SIGNAL(infoMessage(QString,int)) );
        connect( m_job, SIGNAL(finished(bool)), this, SIGNAL(finished(bool)) );
        connect( m_job, SIGNAL(started()), this, SIGNAL(started()) );
        connect( m_job, SIGNAL(canceled()), this, SIGNAL(canceled()) );
        connect( m_job, SIGNAL(percent(int)), this, SLOT(slotProgress(int)) );
        connect( m_job, SIGNAL(subPercent(int)), this, SLOT(slotSubProgress(int)) );
        connect( m_job, SIGNAL(nextTrack(int,int)), this, SIGNAL(nextTrack(int,int)) );

        if( m_job->inherits( "K3b::BurnJob" ) ) {
            connect( m_job, SIGNAL(bufferStatus(int)), this, SIGNAL(buffer(int)) );
            connect( m_job, SIGNAL(deviceBuffer(int)), this, SIGNAL(deviceBuffer(int)) );
        }
    }
Ejemplo n.º 2
0
void K3b::DvdFormattingJob::start()
{
    d->canceled = false;
    d->running = true;
    d->error = false;

    jobStarted();

    if( !d->device ) {
        emit infoMessage( i18n("No device set"), MessageError );
        d->running = false;
        jobFinished(false);
        return;
    }

    // FIXME: check the return value
    if( K3b::isMounted( d->device ) ) {
        emit infoMessage( i18n("Unmounting medium"), MessageInfo );
        K3b::unmount( d->device );
    }

    //
    // first wait for a dvd+rw, dvd-rw, or bd-re
    // Be aware that an empty DVD-RW might be reformatted to another writing mode
    // so we also wait for empty dvds
    //
    if( waitForMedium( d->device,
                       Device::STATE_COMPLETE|Device::STATE_INCOMPLETE|Device::STATE_EMPTY,
                       Device::MEDIA_REWRITABLE_DVD|Device::MEDIA_BD_RE,
                       0,
                       i18n("Please insert a rewritable DVD or Blu-ray medium into drive<p><b>%1 %2 (%3)</b>.",
                            d->device->vendor(),
                            d->device->description(),
                            d->device->blockDeviceName()) ) == Device::MEDIA_UNKNOWN ) {
        emit canceled();
        d->running = false;
        jobFinished(false);
        return;
    }

    emit infoMessage( i18n("Checking medium"), MessageInfo );
    emit newTask( i18n("Checking medium") );

    connect( Device::sendCommand( Device::DeviceHandler::CommandDiskInfo, d->device ),
             SIGNAL(finished(K3b::Device::DeviceHandler*)),
             this,
             SLOT(slotDeviceHandlerFinished(K3b::Device::DeviceHandler*)) );
}
Ejemplo n.º 3
0
void SMTWorker::run()
{
	assert(m_pCT);

	while (!isStopped())
	{
		MCFThreadStatus status = m_pCT->getStatus(m_uiId);

		while (status ==  MCFThreadStatus::SF_STATUS_PAUSE)
		{
			gcSleep(500);
			status = m_pCT->getStatus(m_uiId);
		}

		if (status ==  MCFThreadStatus::SF_STATUS_STOP)
			break;

		if (status ==  MCFThreadStatus::SF_STATUS_NULL)
		{
			if (!newTask())
				continue;
		}

		//make sure we dont do compression if we are ment to be stopped
		if (!isStopped() && status ==  MCFThreadStatus::SF_STATUS_CONTINUE)
		{
			try
			{
				doWork();
			}
			catch (gcException &e)
			{
				gcString name("Null File");

				if (m_pCurFile)
					name = m_pCurFile->getName();

				gcException e2((ERROR_ID)e.getErrId(), e.getSecErrId(), gcString("{0} [{1}]", e.getErrMsg(), name));

				finishTask();
				m_pCT->reportError(m_uiId, e2);
				return;
			}
		}
	}

	m_phFhSink->close();
}
Ejemplo n.º 4
0
Task * pT()
{
	Task * task = NULL;
	tCmd * cmd;

	if (cur_l->type == LEX_EOL)
	{
		waitLex();
		return NULL;
	}
	else if (cur_l->type == LEX_EOF)
		return NULL;

	cmd = pS();

	if (cmd == NULL)
		return NULL;

	task = newTask();

	if (cur_l->type == LEX_BG)
	{
		if (glhard())
		{
			delTask(&task);
			delTCmd(&cmd);
			return NULL;
		}
		task->modeBG = 1;
	}

	if (cur_l->type != LEX_EOL &&
		cur_l->type != LEX_EOF)
	{
		setParserError(PE_UNEXPECTED_END_OF_COMMAND);
		delTask(&task);
		delTCmd(&cmd);
		return NULL;
	}

	task->root = cmd;
	task->cur = cmd;

	waitLex();

	return task;
}
void AddTaskDialog::on_buttonBox_accepted()
{

    //Creation of the task
    Task newTask(0,
              ui->prioritySpinBox->text().toInt(),
              ui->effortSpinBox->text().toInt(),
              ui->nameLineEdit->text(),
              ui->plainTextEdit->toPlainText());

    //Inset the task into the DB
    coll->addItem(newTask.getName(),
                          newTask.getImportance(),
                          newTask.getDurationInH(),
                          newTask.getDescription(),
                          0);
}
Ejemplo n.º 6
0
Archivo: Task.c Proyecto: Eufavn/ghc
static Task *
allocTask (void)
{
    Task *task;

    task = myTask();
    if (task != NULL) {
        return task;
    } else {
        task = newTask(rtsFalse);
#if defined(THREADED_RTS)
        task->id = osThreadId();
#endif
        setMyTask(task);
        return task;
    }
}
Ejemplo n.º 7
0
void SFTWorker::run()
{
	assert(m_pCT);

	while (true)
	{
		uint32 status = m_pCT->getStatus(m_uiId);
		int32 res = BZ_OK;

		while (status == BaseMCFThread::SF_STATUS_PAUSE)
		{
			gcSleep(500);
			status = m_pCT->getStatus(m_uiId);
		}

		if (status == BaseMCFThread::SF_STATUS_STOP)
		{
			break;
		}
		else if (status == BaseMCFThread::SF_STATUS_NULL)
		{
			if (!newTask())
				gcSleep(500);

			continue;
		}
		else if (status == BaseMCFThread::SF_STATUS_ENDFILE)
		{
			do
			{
				res = doWork();
				if (bzErrorCheck(res))
					break;
			}
			while (res != BZ_STREAM_END);
		}
		else if (status == BaseMCFThread::SF_STATUS_CONTINUE)
		{
			res = doWork();
			bzErrorCheck(res);
		}

		if (res == BZ_STREAM_END || status == BaseMCFThread::SF_STATUS_SKIP)
			finishFile();
	}
}
Ejemplo n.º 8
0
void K3bDvdFormattingJob::start()
{
  d->canceled = false;
  d->running = true;
  d->error = false;

  jobStarted();

  if( !d->device ) {
    emit infoMessage( i18n("No device set"), ERROR );
    d->running = false;
    jobFinished(false);
    return;
  }

  // FIXME: check the return value
  if( K3b::isMounted( d->device ) ) {
      emit infoMessage( i18n("Unmounting medium"), INFO );
      K3b::unmount( d->device );
  }

  //
  // first wait for a dvd+rw or dvd-rw
  // Be aware that an empty DVD-RW might be reformatted to another writing mode
  // so we also wait for empty dvds
  //
  if( waitForMedia( d->device,
		    K3bDevice::STATE_COMPLETE|K3bDevice::STATE_INCOMPLETE|K3bDevice::STATE_EMPTY,
		    K3bDevice::MEDIA_WRITABLE_DVD,
		    i18n("Please insert a rewritable DVD medium into drive<p><b>%1 %2 (%3)</b>.")
		    .arg(d->device->vendor()).arg(d->device->description()).arg(d->device->devicename()) ) == -1 ) {
    emit canceled();
    d->running = false;
    jobFinished(false);
    return;
  }

  emit infoMessage( i18n("Checking media..."), INFO );
  emit newTask( i18n("Checking media") );

  connect( K3bDevice::sendCommand( K3bDevice::DeviceHandler::NG_DISKINFO, d->device ),
	   SIGNAL(finished(K3bDevice::DeviceHandler*)),
	   this,
	   SLOT(slotDeviceHandlerFinished(K3bDevice::DeviceHandler*)) );
}
Ejemplo n.º 9
0
Misc::WGTSuperBlock* WGTController::newTask(uint32 id, uint32 &status)
{
	WGTWorkerInfo* worker = findWorker(id);
	assert(worker);

	status = worker->status;

	if (worker->status != SF_STATUS_CONTINUE)
		return NULL;

	if (worker->curBlock)
		return worker->curBlock;

	m_pFileMutex.lock();
	size_t listSize = m_vSuperBlockList.size();
	m_pFileMutex.unlock();

	if (listSize == 0 && !stealBlocks())
	{
		m_pUPThread->stopThread(id);
		worker->status = SF_STATUS_STOP;
		status = SF_STATUS_STOP;

		m_iRunningWorkers--;
		//get thread running again.
		m_WaitCondition.notify();

		return NULL;
	}

	m_pFileMutex.lock();
	Misc::WGTSuperBlock* temp = m_vSuperBlockList.front();
	m_vSuperBlockList.pop_front();
	m_pFileMutex.unlock();

	if (!temp)
		return newTask(id, status);

	worker->curBlock = temp;
	worker->status = SF_STATUS_CONTINUE;
	status = SF_STATUS_CONTINUE;

	return temp;
}
Ejemplo n.º 10
0
Game::Game(Mode::Type mode, QObject *parent):
    QObject(parent),
    m_currentTask(nullptr),
    m_currentVideoTask(nullptr),
    m_currentAnnotationTask(nullptr),
    m_points(0),
    m_multiplier(1),
    m_tasksAnswered(0),
    m_tasksAnsweredCorrectly(0),
    m_maxPoints(0),
    m_mode(mode)
{
    if(mode == Mode::VIDEO)
        newVideoTask();
    if(mode == Mode::DRAG)
        newAnnotationTask();
    else
        newTask();
}
Ejemplo n.º 11
0
mainScreen::mainScreen(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::mainScreen)
{
    ui->setupUi(this);

    //Set variables
    _staw = NULL;
    _stsw = NULL;
    _stiw = NULL;
    _stmw = NULL;
    _blur = new QGraphicsBlurEffect(this);
    _blur->setEnabled(false);
    _showTaskInfo = NULL;
    _showAddSubTask = NULL;

#ifdef ANDROID
    _blur->setBlurRadius(5);
#else
    _blur->setBlurRadius(2);
#endif

    //Create directory where data is stored if
    //it doesn't exist
    if(!QDir(DATADIR).exists())
        QDir().mkdir(DATADIR);

    //Create a task Manager & load Data
    _stm = new SimpleTaskManager();
    _stm->setSaveDir(DATADIR);
    this->loadInitData();

    //Create the Permanent Windows
    _stlw = new SimpleTaskListWindow(_stm, this);
    connect(_stlw, SIGNAL(newTask()), this, SLOT(showAddTask()));
    connect(_stlw, SIGNAL(showTaskInfo(simpleTaskListWidget*)), this, SLOT(showTaskInfo(simpleTaskListWidget*)));
    connect(_stlw, SIGNAL(showTaskMenu(simpleTaskListWidget*)), this, SLOT(showTaskListMenu(simpleTaskListWidget*)));

    //Show the default Window
    this->showTaskList();

    _stlw->setGraphicsEffect(_blur);
}
Ejemplo n.º 12
0
void K3b::VcdJob::startWriterjob()
{
    qDebug() << QString( "(K3b::VcdJob) writing copy %1 of %2" ).arg( m_currentcopy ).arg( m_doc->copies() );
    if ( prepareWriterJob() ) {
        if ( waitForMedium( m_doc->burner() ) == Device::MEDIA_UNKNOWN ) {
            cancel();
            return ;
        }
        // just to be sure we did not get canceled during the async discWaiting
        if ( m_canceled )
            return ;

        if ( m_doc->copies() > 1 )
            emit newTask( i18n( "Writing Copy %1 of %2" , m_currentcopy , m_doc->copies() ) );

        emit burning( true );
        m_writerJob->start();
    }
}
Ejemplo n.º 13
0
Dali::RenderTask RenderTaskList::CreateTask()
{
  RenderTask* taskImpl = RenderTask::New( mIsSystemLevel );

  Dali::RenderTask newTask( taskImpl );
  mTasks.push_back( newTask );

  if ( mSceneObject )
  {
    SceneGraph::RenderTask* sceneObject = taskImpl->CreateSceneObject();
    DALI_ASSERT_DEBUG( NULL != sceneObject );

    // Pass ownership to SceneGraph::RenderTaskList
    AddTaskMessage( mEventToUpdate, *mSceneObject, *sceneObject );
  }

  // Set the default source & camera actors
  taskImpl->SetSourceActor( &mDefaults.GetDefaultRootActor() );
  taskImpl->SetCameraActor( &mDefaults.GetDefaultCameraActor() );

  return newTask;
}
Ejemplo n.º 14
0
Archivo: Task.c Proyecto: A1kmm/ghc
void
startWorkerTask (Capability *cap)
{
  int r;
  OSThreadId tid;
  Task *task;

  // A worker always gets a fresh Task structure.
  task = newTask(rtsTrue);

  // The lock here is to synchronise with taskStart(), to make sure
  // that we have finished setting up the Task structure before the
  // worker thread reads it.
  ACQUIRE_LOCK(&task->lock);

  // We don't emit a task creation event here, but in workerStart,
  // where the kernel thread id is known.
  task->cap = cap;

  // Give the capability directly to the worker; we can't let anyone
  // else get in, because the new worker Task has nowhere to go to
  // sleep so that it could be woken up again.
  ASSERT_LOCK_HELD(&cap->lock);
  cap->running_task = task;

  r = createOSThread(&tid, (OSThreadProc*)workerStart, task);
  if (r != 0) {
    sysErrorBelch("failed to create OS thread");
    stg_exit(EXIT_FAILURE);
  }

  debugTrace(DEBUG_sched, "new worker task (taskCount: %d)", taskCount);

  task->id = tid;

  // ok, finished with the Task struct.
  RELEASE_LOCK(&task->lock);
}
Ejemplo n.º 15
0
MCFCore::MCFFile* SMTController::newTask(uint32 id)
{
	SMTWorkerInfo* worker = findWorker(id);
	assert(worker);

	if (worker->status != SF_STATUS_NULL)
		return NULL;

	m_pFileMutex.lock();
	size_t listSize = m_vFileList.size();
	m_pFileMutex.unlock();

	if (listSize == 0)
	{
		m_pUPThread->stopThread(id);
		worker->status = SF_STATUS_STOP;

		m_iRunningWorkers--;
		//wake thread up
		m_WaitCond.notify();
		return NULL;
	}

	m_pFileMutex.lock();
	int index = m_vFileList.back();
	m_vFileList.pop_back();
	m_pFileMutex.unlock();

	MCFCore::MCFFile *temp = m_rvFileList[index];

	if (!temp)
		return newTask(id);

	worker->vFileList.push_back(index);
	worker->curFile = temp;
	worker->status = SF_STATUS_CONTINUE;
	return temp;
}
Ejemplo n.º 16
0
void K3bMixedJob::start()
{
  jobStarted();

  m_canceled = false;
  m_errorOccuredAndAlreadyReported = false;
  d->copiesDone = 0;
  d->copies = m_doc->copies();
  m_currentAction = PREPARING_DATA;
  d->maxSpeed = false;

  if( m_doc->dummy() )
    d->copies = 1;

  prepareProgressInformation();

  //
  // Check if all files exist
  //
  QValueList<K3bAudioFile*> nonExistingFiles;
  K3bAudioTrack* track = m_doc->audioDoc()->firstTrack();
  while( track ) {
    K3bAudioDataSource* source = track->firstSource();
    while( source ) {
      if( K3bAudioFile* file = dynamic_cast<K3bAudioFile*>( source ) ) {
	if( !QFile::exists( file->filename() ) )
	  nonExistingFiles.append( file );
      }
      source = source->next();
    }
    track = track->next();
  }
  if( !nonExistingFiles.isEmpty() ) {
    if( questionYesNo( "<p>" + i18n("The following files could not be found. Do you want to remove them from the "
				    "project and continue without adding them to the image?") +
		       "<p>" + createNonExistingFilesString( nonExistingFiles, 10 ),
		       i18n("Warning"),
		       i18n("Remove missing files and continue"),
		       i18n("Cancel and go back") ) ) {
      for( QValueList<K3bAudioFile*>::const_iterator it = nonExistingFiles.begin();
	   it != nonExistingFiles.end(); ++it ) {
	delete *it;
      }
    }
    else {
      m_canceled = true;
      emit canceled();
      jobFinished(false);
      return;
    }
  }

  //
  // Make sure the project is not empty
  //
  if( m_doc->audioDoc()->numOfTracks() == 0 ) {
    emit infoMessage( i18n("Please add files to your project first."), ERROR );
    jobFinished(false);
    return;
  }


  // set some flags that are needed
  m_doc->audioDoc()->setOnTheFly( m_doc->onTheFly() );  // for the toc writer
  m_doc->audioDoc()->setHideFirstTrack( false );   // unsupported
  m_doc->dataDoc()->setBurner( m_doc->burner() );  // so the isoImager can read ms data

  emit newTask( i18n("Preparing data") );

  determineWritingMode();

  //
  // First we make sure the data portion is valid
  //

  // we do not have msinfo yet
  m_currentAction = INITIALIZING_IMAGER;
  m_isoImager->setMultiSessionInfo( QString::null );
  m_isoImager->init();
}
Ejemplo n.º 17
0
void K3bDvdFormattingJob::startFormatting( const K3bDevice::DiskInfo& diskInfo )
{
  //
  // Now check the media type:
  // if DVD-RW: use d->mode
  //            emit warning if formatting is full and stuff
  //
  // in overwrite mode: emit info that progress might stop before 100% since formatting will continue
  //                    in the background once the media gets rewritten (only DVD+RW?)
  //

  // emit info about what kind of media has been found

  if( !(diskInfo.mediaType() & (K3bDevice::MEDIA_DVD_RW|
				K3bDevice::MEDIA_DVD_RW_SEQ|
				K3bDevice::MEDIA_DVD_RW_OVWR|
				K3bDevice::MEDIA_DVD_PLUS_RW)) ) {
    emit infoMessage( i18n("No rewritable DVD media found. Unable to format."), ERROR );
    d->running = false;
    jobFinished(false);
    return;
  }


  bool format = true;  // do we need to format
  bool blank = false;  // blank is for DVD-RW sequential incremental
  // DVD-RW restricted overwrite and DVD+RW uses the force option (or no option at all)



  //
  // DVD+RW is quite easy to handle. There is only one possible mode and it is always recommended to not
  // format it more than once but to overwrite it once it is formatted
  // Once the initial formatting has been done it's always "appendable" (or "complete"???)
  //


  if( diskInfo.mediaType() == K3bDevice::MEDIA_DVD_PLUS_RW ) {
    emit infoMessage( i18n("Found %1 media.").arg(K3bDevice::mediaTypeString(K3bDevice::MEDIA_DVD_PLUS_RW)),
		      INFO );

    // mode is ignored

    if( diskInfo.empty() ) {
      //
      // The DVD+RW is blank and needs to be initially formatted
      //
      blank = false;
    }
    else {
      emit infoMessage( i18n("No need to format %1 media more than once.")
			.arg(K3bDevice::mediaTypeString(K3bDevice::MEDIA_DVD_PLUS_RW)), INFO );
      emit infoMessage( i18n("It may simply be overwritten."), INFO );

      if( d->force ) {
	emit infoMessage( i18n("Forcing formatting anyway."), INFO );
	emit infoMessage( i18n("It is not recommended to force formatting of DVD+RW media."), INFO );
	emit infoMessage( i18n("Already after 10-20 reformats the media might be unusable."), INFO );
	blank = false;
      }
      else {
	format = false;
      }
    }

    if( format )
      emit newSubTask( i18n("Formatting DVD+RW") );
  }



  //
  // DVD-RW has two modes: incremental sequential (the default which is also needed for DAO writing)
  // and restricted overwrite which compares to the DVD+RW mode.
  //

  else {  // MEDIA_DVD_RW
    emit infoMessage( i18n("Found %1 media.").arg(K3bDevice::mediaTypeString(K3bDevice::MEDIA_DVD_RW)),
		      INFO );

    if( diskInfo.currentProfile() != K3bDevice::MEDIA_UNKNOWN ) {
      emit infoMessage( i18n("Formatted in %1 mode.").arg(K3bDevice::mediaTypeString(diskInfo.currentProfile())), INFO );


      //
      // Is it possible to have an empty DVD-RW in restricted overwrite mode???? I don't think so.
      //

      if( diskInfo.empty() &&
	  (d->mode == K3b::WRITING_MODE_AUTO ||
	   (d->mode == K3b::WRITING_MODE_INCR_SEQ &&
	    diskInfo.currentProfile() == K3bDevice::MEDIA_DVD_RW_SEQ) ||
	   (d->mode == K3b::WRITING_MODE_RES_OVWR &&
	    diskInfo.currentProfile() == K3bDevice::MEDIA_DVD_RW_OVWR) )
	  ) {
	emit infoMessage( i18n("Media is already empty."), INFO );
	if( d->force )
	  emit infoMessage( i18n("Forcing formatting anyway."), INFO );
	else
	  format = false;
      }
      else if( diskInfo.currentProfile() == K3bDevice::MEDIA_DVD_RW_OVWR &&
	       d->mode != K3b::WRITING_MODE_INCR_SEQ ) {
	emit infoMessage( i18n("No need to format %1 media more than once.")
			  .arg(K3bDevice::mediaTypeString(diskInfo.currentProfile())), INFO );
	emit infoMessage( i18n("It may simply be overwritten."), INFO );

	if( d->force )
	  emit infoMessage( i18n("Forcing formatting anyway."), INFO );
	else
	  format = false;
      }


      if( format ) {
	if( d->mode == K3b::WRITING_MODE_AUTO ) {
	  // just format in the same mode as the media is currently formatted
	  blank = (diskInfo.currentProfile() == K3bDevice::MEDIA_DVD_RW_SEQ);
	}
	else {
	  blank = (d->mode == K3b::WRITING_MODE_INCR_SEQ);
	}

	emit newSubTask( i18n("Formatting"
			      " DVD-RW in %1 mode.").arg(K3bDevice::mediaTypeString( blank ?
										     K3bDevice::MEDIA_DVD_RW_SEQ :
										     K3bDevice::MEDIA_DVD_RW_OVWR )) );
      }
    }
    else {
      emit infoMessage( i18n("Unable to determine the current formatting state of the DVD-RW media."), ERROR );
      d->running = false;
      jobFinished(false);
      return;
    }
  }


  if( format ) {
    delete d->process;
    d->process = new K3bProcess();
    d->process->setRunPrivileged(true);
    //      d->process->setSuppressEmptyLines(false);
    connect( d->process, SIGNAL(stderrLine(const QString&)), this, SLOT(slotStderrLine(const QString&)) );
    connect( d->process, SIGNAL(processExited(KProcess*)), this, SLOT(slotProcessFinished(KProcess*)) );

    d->dvdFormatBin = k3bcore->externalBinManager()->binObject( "dvd+rw-format" );
    if( !d->dvdFormatBin ) {
      emit infoMessage( i18n("Could not find %1 executable.").arg("dvd+rw-format"), ERROR );
      d->running = false;
      jobFinished(false);
      return;
    }

    if( !d->dvdFormatBin->copyright.isEmpty() )
      emit infoMessage( i18n("Using %1 %2 - Copyright (C) %3").arg(d->dvdFormatBin->name()).arg(d->dvdFormatBin->version).arg(d->dvdFormatBin->copyright), INFO );


    *d->process << d->dvdFormatBin;

    if( d->dvdFormatBin->version >= K3bVersion( 4, 6 ) )
      *d->process << "-gui";

    QString p;
    if( blank )
      p = "-blank";
    else
      p = "-force";
    if( !d->quick )
      p += "=full";

    *d->process << p;

    *d->process << d->device->blockDeviceName();

    // additional user parameters from config
    const QStringList& params = d->dvdFormatBin->userParameters();
    for( QStringList::const_iterator it = params.begin(); it != params.end(); ++it )
      *d->process << *it;

    kdDebug() << "***** dvd+rw-format parameters:\n";
    const QValueList<QCString>& args = d->process->args();
    QString s;
    for( QValueList<QCString>::const_iterator it = args.begin(); it != args.end(); ++it ) {
      s += *it + " ";
    }
    kdDebug() << s << endl << flush;
    emit debuggingOutput( "dvd+rw-format command:", s );

    if( !d->process->start( KProcess::NotifyOnExit, KProcess::All ) ) {
      // something went wrong when starting the program
      // it "should" be the executable
      kdDebug() << "(K3bDvdFormattingJob) could not start " << d->dvdFormatBin->path << endl;
      emit infoMessage( i18n("Could not start %1.").arg(d->dvdFormatBin->name()), K3bJob::ERROR );
      d->running = false;
      jobFinished(false);
    }
    else {
      emit newTask( i18n("Formatting") );
    }
  }
  else {
Ejemplo n.º 18
0
bool CKReader::read(const std::string& inputFile, const std::string& thermoDatabase, 
		    const std::string& logfile) {

    clock_t t0, t1;

    t0 = clock();

    ifstream ckinfile(inputFile.c_str());
    ofstream log(logfile.c_str());
    try {
    // construct a parser for the input file
    CKParser parser(&ckinfile, inputFile, &log);
    parser.verbose = verbose;
    parser.debug = debug;

    // write header information to the log file
    struct tm *newtime;
    time_t aclock;
    time( &aclock );                  /* Get time in seconds */
    newtime = localtime( &aclock );   /* Convert time to struct tm form */

    
    log << "CKReader version 1.0" << endl
        << "http://www.cantera.org" << endl << endl
        << asctime(newtime) << endl
        << setw(20) << "input file: " 
        << setw(30) << inputFile << endl;
    
    if (thermoDatabase != "") 
        log << setw(20) << "species database: " 
            << setw(30) << thermoDatabase << endl;
    
    if (!validate) 
        log << endl << "***************  Warning  ***************" << endl
            <<         "     mechanism validation disabled"        << endl
            <<         "*****************************************" << endl;

    if (debug) {
        log << "*** DEBUG MODE ***" << endl;
    }
    else {
        log << "debugging disabled." << endl;
    }

    //-----------   process ELEMENT section  ----------------------

    bool elok = parser.readElementSection(elements);
    int nel = static_cast<int>(elements.size());
    vector<string> elementSymbols;
    for (int j = 0; j < nel; j++) elementSymbols.push_back(elements[j].name);

    if (verbose) {
        log.flags(ios::showpoint);
        log.precision(6);
        log.width(0);

        log << endl << newTask("reading elements") << endl;
    
        // write summary to log file
        for (int i = 0; i < nel; i++) {
            log << i+1 << ".  " << pad(elements[i].name,2) << "  ";
            double wt = elements[i].atomicWeight;
            if (wt == 0.0) log << "<error>";
            else log << wt;
            if (!elements[i].weightFromDB) log << " (specified)";
            if (elements[i].comment != "") 
                log << "      ! " << elements[i].comment;
            log << endl;
        }
    }
    log << "\nread " << nel << " elements." << endl;
    
    if (!elok) {
        log << "\nerrors were encountered." << endl;
        return false;
    }
    if (nel == 0) {
        return false;
    }


    //------------   process SPECIES section  ------------------------

    vector<string> speciesSymbols;
    bool spok = parser.readSpeciesSection(species);
    int nsp = static_cast<int>(species.size());

    if (verbose) log << newTask("reading species") << endl;

    for (int i = 0; i < nsp; i++) {
        Species& s = species[i];
        if (verbose) log << i+1 << ".  " << s.name << endl;
        speciesSymbols.push_back(s.name);
    }
    log << "\nread " << nsp << " species." << endl;

    if (!spok) {
        log << "\nerrors were encountered." << endl;
        return false;
    }
    if (nsp == 0) return false;


    //-------------   process THERMO section  -------------------------

    if (verbose) log << newTask("looking up species definitions") << endl;

    // if a thermo database is specified, get the default Tmin, Tmid, Tmax
    vector_fp temp;

    if (thermoDatabase != "") {

        if (verbose) log << "reading default temperature ranges from " 
                         << thermoDatabase  << endl;

        ifstream thermofile(thermoDatabase.c_str());
        CKParser thermReader(&thermofile, thermoDatabase, &log);
        thermReader.verbose = verbose;
        thermReader.debug = debug;
        int dbflag = HasTempRange;
        vector<string> dummy;
        thermReader.readThermoSection(dummy, speciesData, temp, dbflag, log);
    }

    
    bool hasthermo = parser.advanceToKeyword("THERM","REAC");

    int k, optionFlag = 0;
    int undefined = static_cast<int>(species.size());
    string nm;
    vector<string> undef;
    bool allsp = (speciesSymbols[0] == "<ALL>");
    if (hasthermo && 
	parser.readThermoSection(speciesSymbols,
				 speciesData, temp, optionFlag, log)) {
        if (allsp) {
            nsp = static_cast<int>(speciesData.size()); 
            for (k = 0; k < nsp; k++) {
                Species s;
                s.name = speciesSymbols[k];
                species.push_back(s);
            }
        }
        undefined = 0;
        for (k = 0; k < nsp; k++) {
            nm = species[k].name;
            species[k] = speciesData[species[k].name];
            if (species[k].name == "<empty>") {
                undefined++;
                undef.push_back(nm);
                species[k].name = nm;
            }
        }
        int localdefs = nsp - undefined;
        if (localdefs > 0 && verbose) log << "found definitions for " 
                                          << localdefs 
                                          << " of " 
                                          << nsp 
                                          << " species in the input file. " 
                                          << endl;
    }
    else {
        undef = speciesSymbols;
        if (verbose) log << "no THERMO section in input file." << endl;
    }

    if (undefined > 0 && thermoDatabase != "" 
        && optionFlag != NoThermoDatabase) {

        if (verbose) log << "searching external database " 
                         << thermoDatabase << " for species definitions..."
                         << endl;

        ifstream thermofile(thermoDatabase.c_str());
        CKParser thermoReader(&thermofile, thermoDatabase, &log);
        thermoReader.verbose = verbose;
        thermoReader.debug = debug;
        int dbflag = HasTempRange;
        thermoReader.readThermoSection(undef, speciesData, temp, dbflag, log);
        undefined = 0;
        if (allsp) {
            species.clear();
            nsp = static_cast<int>(speciesData.size()); 
            for (k = 0; k < nsp; k++) {
                Species s;
                s.name = undef[k];
                species.push_back(s);
            }
        }
        for (int k = 0; k < nsp; k++) {
            if (species[k].valid == 0) {
                nm = species[k].name;
                species[k] = speciesData[species[k].name];
                if (species[k].name == "<empty>") {
                    undefined++;
                    species[k].name = nm;
                }
            }
        }
    }

    if (validate && !validateSpecies(log)) {
      //Cantera::setError("read","error in species");
        return false;
    }


    //-------------   process REACTIONS section  -------------------------

    if (verbose) log << newTask("reading reactions") << endl;

    ckinfile.close();
    ifstream ckinfile2(inputFile.c_str());

    // construct a new parser for the input file
    CKParser parser2(&ckinfile2, inputFile, &log);
    parser2.verbose = verbose;
    parser2.debug = debug;

    parser2.readReactionSection(speciesSymbols, elementSymbols, reactions, units);
    log << "\nread " << static_cast<int>(reactions.size()) 
		<< " reactions." << endl;

    bool rxnok = true;
    if (validate) rxnok = rxnok && validateReactions(log);
    bool writeok = true;
    if (verbose || validate)  writeok = writeReactions(log);
    rxnok = rxnok && writeok;
    if (!rxnok) return false;

    log << "\nSuccess... ";
    t1 = clock();
    log << "elapsed CPU time = " 
        << double(t1 - t0)/CLOCKS_PER_SEC 
        << " s" << endl;
    if (!validate) log << "*** no validation performed ***" << endl;
    }

    catch (CK_Exception e) {
        log << e.errorMessage() << endl;
        //Cantera::setError("CKReader::read",e.errorMessage());
        return false;
    }
    catch (...) {
        log << "an exception was raised in CKReader.";
        return false;
    }

    return true;
}
Ejemplo n.º 19
0
void K3b::VcdJob::vcdxBuild()
{
    emit newTask( i18n( "Creating image files" ) );

    m_stage = stageUnknown;
    firstTrack = true;
    delete m_process;
    m_process = new K3b::Process();
    m_process->setSplitStdout( true );

    emit infoMessage( i18n( "Creating Cue/Bin files..." ), K3b::Job::MessageInfo );
    const K3b::ExternalBin* bin = k3bcore ->externalBinManager() ->binObject( "vcdxbuild" );
    if ( !bin ) {
        qDebug() << "(K3b::VcdJob) could not find vcdxbuild executable";
        emit infoMessage( i18n( "Could not find %1 executable." , QString("vcdxbuild") ), K3b::Job::MessageError );
        emit infoMessage( i18n( "To create Video CDs you have to install VcdImager version %1." ,QString( ">= 0.7.12") ), K3b::Job::MessageInfo );
        emit infoMessage( i18n( "You can find this on your distribution disks or download it from http://www.vcdimager.org" ), K3b::Job::MessageInfo );
        cancelAll();
        jobFinished( false );
        return ;
    }

    if ( bin->version() < K3b::Version( "0.7.12" ) ) {
        qDebug() << "(K3b::VcdJob) vcdxbuild executable too old!";
        emit infoMessage( i18n( "%1 executable too old: need version %2 or greater." ,QString( "Vcdxbuild" ),QString( "0.7.12" )), K3b::Job::MessageError );
        emit infoMessage( i18n( "You can find this on your distribution disks or download it from http://www.vcdimager.org" ), K3b::Job::MessageInfo );
        cancelAll();
        jobFinished( false );
        return ;
    }

    if ( !bin->copyright().isEmpty() )
        emit infoMessage( i18n( "Using %1 %2 – Copyright © %3" , bin->name() , bin->version() ,bin->copyright() ), MessageInfo );

    *m_process << bin;

    // additional user parameters from config
    const QStringList& params = k3bcore->externalBinManager() ->program( "vcdxbuild" ) ->userParameters();
    for ( QStringList::const_iterator it = params.begin(); it != params.end(); ++it )
        *m_process << *it;


    if ( vcdDoc() ->vcdOptions() ->Sector2336() ) {
        qDebug() << "(K3b::VcdJob) Write 2336 Sectors = on";
        *m_process << "--sector-2336";
    }

    *m_process << "--progress" << "--gui";

    *m_process << QString( "--cue-file=%1" ).arg( m_cueFile );

    *m_process << QString( "--bin-file=%1" ).arg( m_doc->vcdImage() );

    *m_process << d->xmlFile->fileName();

    connect( m_process, SIGNAL(stdoutLine(QString)),
             this, SLOT(slotParseVcdxBuildOutput(QString)) );
    connect( m_process, SIGNAL(finished(int,QProcess::ExitStatus)),
             this, SLOT(slotVcdxBuildFinished(int,QProcess::ExitStatus)) );

    // vcdxbuild commandline parameters
    qDebug() << "***** vcdxbuild parameters:";
    QString s = m_process->joinedArgs();
    qDebug() << s << flush;
    emit debuggingOutput( "vcdxbuild command:", s );

    if ( !m_process->start( KProcess::MergedChannels ) ) {
        qDebug() << "(K3b::VcdJob) could not start vcdxbuild";
        emit infoMessage( i18n( "Could not start %1." , QString("vcdxbuild") ), K3b::Job::MessageError );
        cancelAll();
        jobFinished( false );
    }
}
Ejemplo n.º 20
0
void K3b::DvdFormattingJob::startFormatting( const Device::DiskInfo& diskInfo )
{
    //
    // Now check the media type:
    // if DVD-RW: use d->mode
    //            emit warning if formatting is full and stuff
    //
    // in overwrite mode: emit info that progress might stop before 100% since formatting will continue
    //                    in the background once the media gets rewritten (only DVD+RW/BD-RE?)
    //


    // emit info about what kind of media has been found
    if( diskInfo.mediaType() & (Device::MEDIA_REWRITABLE_DVD | Device::MEDIA_BD_RE) ) {
        emit infoMessage( i18n("Found %1 medium.", Device::mediaTypeString(diskInfo.mediaType())),
                        MessageInfo );
    }
    else {
        emit infoMessage( i18n("No rewritable DVD or BD medium found. Unable to format."), MessageError );
        d->running = false;
        jobFinished(false);
        return;
    }

    bool format = true;  // do we need to format
    bool blank = false;  // blank is for DVD-RW sequential incremental
    // DVD-RW restricted overwrite and DVD+RW uses the force option (or no option at all)

    //
    // DVD+RW/BD-RE is quite easy to handle. There is only one possible mode and it is always recommended to not
    // format it more than once but to overwrite it once it is formatted
    // Once the initial formatting has been done it's always "appendable" (or "complete"???)
    //

    if( diskInfo.mediaType() & (Device::MEDIA_DVD_PLUS_ALL | Device::MEDIA_BD_RE) ) {

        if( diskInfo.empty() ) {
            //
            // The DVD+RW/BD is blank and needs to be initially formatted
            //
            blank = false;
        }
        else {
            emit infoMessage( i18n("No need to format %1 media more than once.",
                                   Device::mediaTypeString(diskInfo.mediaType())), MessageInfo );
            emit infoMessage( i18n("It may simply be overwritten."), MessageInfo );

            if( d->force ) {
                emit infoMessage( i18n("Forcing formatting anyway."), MessageInfo );
                emit infoMessage( i18n("It is not recommended to force formatting of %1 media.",
                                       Device::mediaTypeString(diskInfo.mediaType())), MessageInfo );
                emit infoMessage( i18n("After 10-20 reformats the media might become unusable."), MessageInfo );
                blank = false;
            }
            else {
                format = false;
            }
        }

        if( format )
            emit newSubTask( i18n("Formatting %1 medium", Device::mediaTypeString(diskInfo.mediaType())) );
    }

    //
    // DVD-RW has two modes: incremental sequential (the default which is also needed for DAO writing)
    // and restricted overwrite which compares to the DVD+RW mode.
    //

    else {  // MEDIA_DVD_RW

        if( diskInfo.currentProfile() != Device::MEDIA_UNKNOWN ) {
            emit infoMessage( i18n("Formatted in %1 mode.",Device::mediaTypeString(diskInfo.currentProfile())), MessageInfo );


            //
            // Is it possible to have an empty DVD-RW in restricted overwrite mode???? I don't think so.
            //

            if( diskInfo.empty() &&
                (d->mode == WritingModeAuto ||
                 (d->mode == WritingModeIncrementalSequential &&
                  diskInfo.currentProfile() == Device::MEDIA_DVD_RW_SEQ) ||
                 (d->mode == WritingModeRestrictedOverwrite &&
                  diskInfo.currentProfile() == Device::MEDIA_DVD_RW_OVWR) )
                ) {
                emit infoMessage( i18n("Media is already empty."), MessageInfo );
                if( d->force )
                    emit infoMessage( i18n("Forcing formatting anyway."), MessageInfo );
                else
                    format = false;
            }
            else if( diskInfo.currentProfile() == Device::MEDIA_DVD_RW_OVWR &&
                     d->mode != WritingModeIncrementalSequential ) {
                emit infoMessage( i18n("No need to format %1 media more than once.",
                                  Device::mediaTypeString(diskInfo.currentProfile())), MessageInfo );
                emit infoMessage( i18n("It may simply be overwritten."), MessageInfo );

                if( d->force )
                    emit infoMessage( i18n("Forcing formatting anyway."), MessageInfo );
                else
                    format = false;
            }

            if( format ) {
                if( d->mode == WritingModeAuto ) {
                    // just format in the same mode as the media is currently formatted
                    blank = (diskInfo.currentProfile() == Device::MEDIA_DVD_RW_SEQ);
                }
                else {
                    blank = (d->mode == WritingModeIncrementalSequential);
                }

                emit newSubTask( i18n("Formatting"
                                      " DVD-RW in %1 mode.",Device::mediaTypeString( blank ?
                                                                                     Device::MEDIA_DVD_RW_SEQ :
                                                                                     Device::MEDIA_DVD_RW_OVWR )) );
            }
        }
        else {
            emit infoMessage( i18n("Unable to determine the current formatting state of the DVD-RW medium."), MessageError );
            d->running = false;
            jobFinished(false);
            return;
        }
    }


    if( format ) {
        delete d->process;
        d->process = new Process();
        connect( d->process, SIGNAL(stderrLine(QString)), this, SLOT(slotStderrLine(QString)) );
        connect( d->process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(slotProcessFinished(int,QProcess::ExitStatus)) );

        d->dvdFormatBin = k3bcore->externalBinManager()->binObject( "dvd+rw-format" );
        if( !d->dvdFormatBin ) {
            emit infoMessage( i18n("Could not find %1 executable.",QString("dvd+rw-format")), MessageError );
            d->running = false;
            jobFinished(false);
            return;
        }

        if( !d->dvdFormatBin->copyright().isEmpty() )
            emit infoMessage( i18n("Using %1 %2 – Copyright © %3",d->dvdFormatBin->name(),d->dvdFormatBin->version(),d->dvdFormatBin->copyright()), MessageInfo );


        *d->process << d->dvdFormatBin;

        if( d->dvdFormatBin->version() >= Version( 4, 6 ) )
            *d->process << "-gui";

        QString p;
        if( blank )
            p = "-blank";
        else
            p = "-force";
        if( d->formattingMode == FormattingComplete )
            p += "=full";

        *d->process << p;

        *d->process << d->device->blockDeviceName();

        // additional user parameters from config
        const QStringList& params = d->dvdFormatBin->userParameters();
        for( QStringList::const_iterator it = params.begin(); it != params.end(); ++it )
            *d->process << *it;

        qDebug() << "***** dvd+rw-format parameters:\n";
        QString s = d->process->joinedArgs();
        qDebug() << s << endl << flush;
        emit debuggingOutput( "dvd+rw-format command:", s );

        if( !d->process->start( KProcess::OnlyStderrChannel ) ) {
            // something went wrong when starting the program
            // it "should" be the executable
            qDebug() << "(K3b::DvdFormattingJob) could not start " << d->dvdFormatBin->path();
            emit infoMessage( i18n("Could not start %1.",d->dvdFormatBin->name()), Job::MessageError );
            d->running = false;
            jobFinished(false);
        }
        else {
            emit newTask( i18n("Formatting") );
        }
    }
    else {
Ejemplo n.º 21
0
bool Manager::createTask(const std::set<std::string> &words,
			 const char *taskName, unsigned maxLimit) {
  if(words.size()==0)
    return false;
  unsigned tasksNum = words.size()/maxLimit + 1;
  maxLimit = words.size()/tasksNum;
  std::string baseName;
  std::string realName;
  std::ofstream desFile;
  std::ostringstream os;

  time_t curTime;
  struct tm * timeinfo;
  char buffer[20];
  std::set<std::string>::const_iterator itr = words.begin();
  time(&curTime);

  
  if(taskName != 0)
    baseName = taskName;

  if(baseName.empty()){
    timeinfo = localtime(&curTime);
    strftime(buffer,20,"%Y%m%d%H%M%S",timeinfo);
    baseName = buffer;
  }

  for (unsigned i = 1; i <= tasksNum; ++i) { //[0]
    memset(buffer,0,20); 
    os.str("");
    os << "_" << i;

    if(tasksNum > 1)
      realName = baseName + os.str();
    else
      realName = baseName;
    if(curTime > maxTaskID)
      maxTaskID = curTime;
    else
      ++maxTaskID;
    desFile.open(Scanner::getTaskFileName(maxTaskID).c_str());
    if(!desFile.is_open()) {
      return false;
    }

    //Write words into file.
    unsigned j = 0;
    while(j++ < maxLimit && itr != words.end()) {
      if(!desFile.good()){
	return false;
      }
      if(itr->empty()) {
	++itr;
	continue;
      }else {
	desFile << *itr << std::endl;
	++itr;
      }
    }
    
    Task newTask(maxTaskID,realName.c_str());
    //Pass a copy of newTask here.
    allTasks[newTask.getID()] = newTask;
    activeID.push_back(newTask.getID());
    desFile.close();
  } //[!0]
  return true;
}
Ejemplo n.º 22
0
bool AudioProjectConvertingJob::init()
{
    emit newTask( i18n("Converting Audio Tracks")  );
    emit infoMessage( i18n("Starting audio conversion."), Job::MessageInfo );
    return true;
}
Ejemplo n.º 23
0
void QuickTaskCreator::taskify(){
    QString text=this->m_ui->editor->toPlainText();
    QRegExp rx("(.*)(\n|$)");
    int pos = 0;
    rx.setMinimal(true);
    //loop through each line
    QString currentTask;
    QStringList tasks;
    QRegExp newTask("^[ |\t|\\s]*([-\\*]|[0-9]+\\.)[ |\t|\\s]*(.+)$");

    newTask.setMinimal(true);
    while ((pos = rx.indexIn(text, pos)) != -1) {
       if(rx.matchedLength()==0)pos++;
       QString line =rx.cap(1);
       pos += rx.matchedLength();
       qDebug()<<"line:" <<line;
       if(newTask.exactMatch(line)||line==""){
            if(currentTask!=""){

                currentTask.replace(QRegExp("^[ |\t|\\s]+"),"");
                tasks << currentTask;
            }
            currentTask="";
            currentTask.append(newTask.cap(2));

       }else {
           if(currentTask!="")currentTask.append("\n");
            currentTask.append(line);
       }



   }
    //handle final task.
   if(currentTask!="")currentTask.append("\n");
    currentTask.append(rx.cap(1));
    if(currentTask!=""){
        currentTask.replace(QRegExp("^[ |\t|\\s]+"),"");
        tasks<<currentTask;
    }

    //remove all widgets if we already have some
    while (this->taskWidgets.count()){
        QuickTaskTask *task;
        task = this->taskWidgets.takeFirst();
        this->taskLayout->removeWidget(task);
        task->deleteLater();
    }
    //add new widgets
    for(int x=0;x<tasks.length();x++){
        qDebug()<<"Task: "<<tasks.at(x);
        QuickTaskTask *task=new QuickTaskTask(this);
            task->setDescription(tasks.at(x));

            task->val["parentTaskID"]=this->defaultsWidget->getParent().toStdString();
            task->val["statusID"]=this->defaultsWidget->getStatus().toStdString();
            task->val["ownerID"]=this->defaultsWidget->getOwner().toStdString();
            this->taskLayout->addWidget(task);
            this->taskWidgets.append(task);
    }
    //this->layout.addWidget(&this->editor);
    this->m_ui->editor->moveCursor(QTextCursor::End);
}
/**
 * routine executed by worker threads.
 *
 * @function   worker_routine
 *
 * @date       2016-01-15
 *
 * @revision   none
 *
 * @designer   Eric Tsang
 *
 * @programmer Eric Tsang
 *
 * @note
 *
 * continuously reads tasks from the tasks vector, executes them, and writes the
 *   results to the results pipe for the parent to receive.
 *
 * once there are no more tasks to execute, the thread terminates.
 *
 * @signature  void* worker_routine(void*)
 */
void* worker_routine(void*)
{
    bool yield = false;

    while(true)
    {
        if (yield)
        {
            pthread_yield();
            yield = false;
        }
        Number* loBoundPtr;

        // get the next task that needs processing
        {
            Lock scopelock(&taskAccess.sem);

            // if there are tasks available to get, get them
            if(!tasks.empty())
            {
                loBoundPtr = tasks.back();
                tasks.pop_back();
            }

            // otherwise, if there are tasks available in the future, wait for
            // them to be available
            else if(!allTasksProduced)
            {
                yield = true;
                continue;
            }

            // otherwise, there are no more tasks, end the loop
            else
            {
                break;
            }
        }
        tasksNotFullSem.post();

        // calculate the hiBound for a task
        Number hiBound;
        mpz_add_ui(hiBound.value,loBoundPtr->value,MAX_NUMBERS_PER_TASK-1);
        if(mpz_cmp(hiBound.value,prime.value) > 0)
        {
            mpz_set(hiBound.value,prime.value);
        }

        // create the task
        FindFactorsTask newTask(prime.value,hiBound.value,loBoundPtr->value);

        // do the processing
        newTask.execute();

        // post results of the tasks
        {
            Lock scopelock(&resultAccess.sem);

            std::vector<mpz_t*>* taskResults = newTask.get_results();
            for(register unsigned int i = 0; i < taskResults->size(); ++i)
            {
                Number* numPtr = new Number();
                mpz_set(numPtr->value,*taskResults->at(i));
                results.push_back(numPtr);
            }
        }

        delete loBoundPtr;
    }

    pthread_exit(0);
}
Ejemplo n.º 25
0
void TraceThread::run() {
	int status;
	long ret;
	pid_t trace_pid;
	unsigned long event_msg;

	setupSignalHandler();

	// attach to processes
	attach();

	// Check if the observed process is traced
	if (tasks.find(pid) == tasks.end()) {
		trace_mutex.unlock();
		context.report(Error::PROC_TRACE, "observed_process", "Cannot trace the observed_process");
	}

	context.info("Attached to all tasks of process " + QString::number(pid));
	trace_mutex.unlock();

	// start the loop for tracking process events
	while (true) {
		context.debug("Trace Thread is waiting");
		// set alarm
		alarm(3);
		trace_pid = waitpid(-1, &status, __WALL);
		alarm(0);

		if (alarm_occured) {
			context.debug("ALARM!");
			alarm_occured = false;

			if (exreq)
				break;
			else if (trace_pid == -1)
				continue;
		}

		if (trace_pid == -1) {
			context.report(Error::PROC_TRACE, "waitpid", "waitpid failed while tracing the observed process");
			continue;
		}

		context.debug("Got signal from: " + QString::number(trace_pid));

		// check return status of waitpid

		if (WIFEXITED(status) || WIFSIGNALED(status)) {
			tasks.erase(trace_pid);

			emit sig_TaskTerminated(trace_pid);

			if (pid == trace_pid) return;
		} else if (WIFSTOPPED(status)) {

			if (WSTOPSIG(status) == SIGTRAP) {
				ret = ptrace(PTRACE_GETEVENTMSG, trace_pid, nullptr, (void *)&event_msg);

				if (ret != 0)
					context.report(Error::PROC_TRACE, "ptrace_eventmsg", "Could not get ptrace event information");

				switch (status >> 16) {
				case (PTRACE_EVENT_CLONE):

				case (PTRACE_EVENT_FORK):

				case (PTRACE_EVENT_VFORK):
					newTask(event_msg);
					break;

				default:
					context.debug("Received unhandled ptrace event!");
					break;
				}

				ptraceContinue(trace_pid);

			} else if (WSTOPSIG(status) == SIGSTOP) {
				context.debug("Received stop signal!");

				if (tasks.find(trace_pid) != tasks.end()) {
					ptraceContinue(trace_pid);
				} else
					newTask(trace_pid);

			} else {
				context.debug("Received unhandled signal!");
				ptraceContinue(trace_pid, WSTOPSIG(status));
			}

		} else {
Ejemplo n.º 26
0
void K3b::AudioCueFileWritingJob::importCueInProject()
{
    // cleanup the project (this wil also delete the decoder)
    // we do not use newDocument as that would overwrite the settings already made
    while( d->audioDoc->firstTrack() )
        delete d->audioDoc->firstTrack()->take();

    d->decoder = 0;

    K3b::CueFileParser parser( d->cueFile );
    if( parser.isValid() && parser.toc().contentType() == K3b::Device::AUDIO ) {

        kDebug() << "(K3b::AudioCueFileWritingJob::importCueFile) parsed with image: " << parser.imageFilename();

        // global cd-text
        d->audioDoc->setTitle( parser.cdText().title() );
        d->audioDoc->setPerformer( parser.cdText().performer() );
        d->audioDoc->writeCdText( !parser.cdText().title().isEmpty() );

        d->decoder = K3b::AudioDecoderFactory::createDecoder( parser.imageFilename() );
        if( d->decoder ) {
            d->decoder->setFilename( parser.imageFilename() );

            K3b::AudioTrack* after = 0;
            K3b::AudioFile* newFile = 0;
            unsigned int i = 0;
            for( K3b::Device::Toc::const_iterator it = parser.toc().constBegin();
                 it != parser.toc().constEnd(); ++it ) {
                const K3b::Device::Track& track = *it;

                newFile = new K3b::AudioFile( d->decoder, d->audioDoc );
                newFile->setStartOffset( track.firstSector() );
                newFile->setEndOffset( track.lastSector()+1 );

                K3b::AudioTrack* newTrack = new K3b::AudioTrack( d->audioDoc );
                newTrack->addSource( newFile );
                newTrack->moveAfter( after );

                // cd-text
                newTrack->setTitle( parser.cdText()[i].title() );
                newTrack->setPerformer( parser.cdText()[i].performer() );

                // add the next track after this one
                after = newTrack;
                ++i;
            }

            // let the last source use the data up to the end of the file
            if( newFile )
                newFile->setEndOffset(0);

            // now analyze the source
            emit newTask( i18n("Analysing the audio file") );
            emit newSubTask( i18n("Analysing %1", parser.imageFilename() ) );

            // start the analyser job
            d->analyserJob->setDecoder( d->decoder );
            d->analyserJob->start();
        }
        else {
            emit infoMessage( i18n("Unable to handle '%1' due to an unsupported format.", d->cueFile ), MessageError );
            jobFinished(false);
        }
    }
    else {
        emit infoMessage( i18n("No valid audio cue file: '%1'", d->cueFile ), MessageError );
        jobFinished(false);
    }
}
Ejemplo n.º 27
0
int BusyMode_RunTasks(BusyTask* tasks, int numTasks)
{
    const char* currentTaskName = NULL;
    BusyTask* task;
    int i, mode;
    int result = 0;

    if(BusyMode_Active())
    {
        App_Error("BusyMode: Internal error, already busy...");
        exit(1); // Unreachable.
    }

    if(!tasks || numTasks <= 0) return result; // Hmm, no work?

    // Pick the first task.
    task = tasks;

    int initialMode = task->mode;
    preBusySetup(initialMode);

    // Process tasks.
    for(i = 0; i < numTasks; ++i, task++)
    {
        // If no new task name is specified, continue using the name of the previous task.
        if(task->name)
        {
            if(task->name[0])
                currentTaskName = task->name;
            else // Clear the name.
                currentTaskName = NULL;
        }

        mode = task->mode;
        /// @todo Kludge: Force BUSYF_STARTUP here so that the animation of one task
        ///       is not drawn on top of the last frame of the previous.
        if(numTasks > 1)
        {
            mode |= BUSYF_STARTUP;
        }
        // kludge end

        // Null tasks are not processed (implicit success).
        if(!task->worker) continue;

        /**
         * Process the work.
         */
#ifdef __CLIENT__
        // Is the worker updating its progress?
        if(task->maxProgress > 0)
            Con_InitProgress2(task->maxProgress, task->progressStart, task->progressEnd);
#endif
        // Invoke the worker in a new thread.
        /// @todo Kludge: Presently a temporary local task is needed so that we can modify
        ///       the task name and mode flags.
        { BusyTask* tmp = newTask(mode, task->worker, task->workerData, currentTaskName);
        result = runTask(tmp);
        // We are now done with this task.
        deleteTask(tmp);

        if(result) break;
        }
        // kludge end.
    }

    postBusyCleanup();

    return result;
}
Ejemplo n.º 28
0
void Renderer::_computeImage()
{
    if (!_integrator) {
        return ;
    }
    int s = qSqrt(config->renderingTaskNumber());

    QSize imageSize = _image.size();
    QSize sectionSize = imageSize / s;

    sectionSize.setWidth(qMax(sectionSize.width(), 1));
    sectionSize.setHeight(qMax(sectionSize.height(), 1));

    QList<QRect> tasks;
    for (int x = 0; x < imageSize.width(); x += sectionSize.width()) {
        for (int y = 0; y < imageSize.height(); y += sectionSize.height()) {
            QRect newTask(QPoint(x, y), sectionSize);

            newTask.setRight(qMin(newTask.right(), imageSize.width() - 1));
            newTask.setBottom(qMin(newTask.bottom(), imageSize.height() - 1));
            tasks.append(newTask);
        }
    }

    _imageColors.resize(imageSize.width() * imageSize.height());
    _imageColors.fill(Color::BLACK);

    _elapsedTime = 0;
    _sampleNumber = 0;
    _renderingTime.restart();

    _integrator->preprocess(_scene, _camera);

    _renderingTime.restart();

    emit renderingStarted();

    QTime saveTime;
    saveTime.restart();
    while (_stopThread == false) {
        _renderingTasks = tasks;

        std::random_shuffle(_renderingTasks.begin(), _renderingTasks.end());

        for (int i = 0; i < config->threadNumber(); ++i) {
            _computingThreads.append(new std::thread(&Renderer::_computeSections, this));
        }

        for (std::thread* computingThread : _computingThreads) {
            computingThread->join();
            delete computingThread;
        }
        _computingThreads.clear();
        _renderingTasks.clear();
        ++_sampleNumber;
        _elapsedTime += _renderingTime.elapsed();
        if (saveTime.elapsed() > 10000) {
            saveTime.restart();
            _image.save(config->outputDir() + "/last.bmp");
        }
        _pauseMutex.lock();
        _pauseMutex.unlock();
        _renderingTime.restart();
    }
    emit renderingFinished();

    _isRendering = false;
}
Ejemplo n.º 29
0
void K3bGrowisofsWriter::start()
{
  jobStarted();

  d->lastWritingSpeed = 0;
  d->lastProgressed = 0;
  d->lastProgress = 0;
  d->firstSizeFromOutput = -1;
  d->lastSpeedCalculationTime = QTime::currentTime();
  d->lastSpeedCalculationBytes = 0;
  d->writingStarted = false;
  d->canceled = false;
  d->speedEst->reset();
  d->finished = false;

  if( !prepareProcess() ) {
    jobFinished( false );
  }
  else {

    kdDebug() << "***** " << d->growisofsBin->name() << " parameters:\n";
    const QValueList<QCString>& args = d->process->args();
    QString s;
    for( QValueList<QCString>::const_iterator it = args.begin(); it != args.end(); ++it ) {
      s += *it + " ";
    }
    kdDebug() << s << flush << endl;
    emit debuggingOutput( d->growisofsBin->name() + " command:", s);


    emit newSubTask( i18n("Preparing write process...") );

    // FIXME: check the return value
    if( K3b::isMounted( burnDevice() ) ) {
      emit infoMessage( i18n("Unmounting medium"), INFO );
      K3b::unmount( burnDevice() );
    }

    // block the device (including certain checks)
    k3bcore->blockDevice( burnDevice() );

    // lock the device for good in this process since it will
    // be opened in the growisofs process
    burnDevice()->close();
    burnDevice()->usageLock();

    if( !d->process->start( KProcess::NotifyOnExit, KProcess::All ) ) {
      // something went wrong when starting the program
      // it "should" be the executable
      kdDebug() << "(K3bGrowisofsWriter) could not start " << d->growisofsBin->path << endl;
      emit infoMessage( i18n("Could not start %1.").arg(d->growisofsBin->name()), K3bJob::ERROR );
      jobFinished(false);
    }
    else {
      if( simulate() ) {
	emit newTask( i18n("Simulating") );
	emit infoMessage( i18n("Starting simulation..."),
			  K3bJob::INFO );
      }
      else {
	emit newTask( i18n("Writing") );
	emit infoMessage( i18n("Starting disc write..."), K3bJob::INFO );
      }

      d->gh->handleStart();

      // create the ring buffer
      if( d->usingRingBuffer ) {
	if( !d->ringBuffer ) {
	  d->ringBuffer = new K3bPipeBuffer( this, this );
	  connect( d->ringBuffer, SIGNAL(percent(int)), this, SIGNAL(buffer(int)) );
	  connect( d->ringBuffer, SIGNAL(finished(bool)), this, SLOT(slotRingBufferFinished(bool)) );
	}

	d->ringBuffer->writeToFd( d->process->stdinFd() );
	bool manualBufferSize = k3bcore->globalSettings()->useManualBufferSize();
	int bufSize = ( manualBufferSize ? k3bcore->globalSettings()->bufferSize() : 20 );
	d->ringBuffer->setBufferSize( bufSize );

	if( !d->image.isEmpty() )
	  d->ringBuffer->readFromFd( d->inputFile.handle() );

	d->ringBuffer->start();
      }
    }
  }