Пример #1
0
void FilesystemWidget::ExtractDirectory(const DiscIO::Partition& partition, const QString& path,
                                        const QString& out)
{
  const DiscIO::FileSystem* filesystem = m_volume->GetFileSystem(partition);
  if (!filesystem)
    return;

  std::unique_ptr<DiscIO::FileInfo> info = filesystem->FindFileInfo(path.toStdString());
  u32 size = info->GetTotalChildren();

  QProgressDialog* dialog = new QProgressDialog(this);
  dialog->setMinimum(0);
  dialog->setMaximum(size);
  dialog->show();

  bool all = path.isEmpty();

  DiscIO::ExportDirectory(
      *m_volume, partition, *info, true, path.toStdString(), out.toStdString(),
      [all, dialog](const std::string& current) {
        dialog->setLabelText(
            (all ? QObject::tr("Extracting All Files...") : QObject::tr("Extracting Directory..."))
                .append(QStringLiteral(" %1").arg(QString::fromStdString(current))));
        dialog->setValue(dialog->value() + 1);

        QCoreApplication::processEvents();
        return dialog->wasCanceled();
      });

  dialog->close();
}
Пример #2
0
void Thread::Execute(bool WaitTilDone) { //starts the thread, waits til complete;
	clock_t startTime, finishTime;
	startTime = clock();

	QProgressDialog progress;
	progress.setModal(true);
	if (pCancelFlag) *pCancelFlag = false; //haven't canceled before we started!

	start(); 

	if (WantProgress) progress.show();

	if (WantProgress || WantTimed || WaitTilDone){ //if we want to stick around until the thread is finished...
		while (isRunning()){
			if (WantProgress){
				progress.setLabelText(QString((*pCurMessage).c_str()));
				progress.setRange(0, *pCurMaxTick);
				progress.setValue(*pCurTick);
				QApplication::processEvents();
				if (progress.wasCanceled()){
					*pCancelFlag = true;
					wait();
					return; //returns
				}
			}
			msleep(50);
		}
	}

	finishTime = clock();
	double duration = (double)(finishTime - startTime) / CLOCKS_PER_SEC;
	std::ostringstream os;
	os << "Elapsed time: " << duration << " Sec";
	if (WantTimed) QMessageBox::warning(NULL, "Warning", (os.str()).c_str());
}
Пример #3
0
/*=========================================================================
  _doFileSearch 
=========================================================================*/
void MainWindow::_doFileSearch (const QString &path, const QString &name, 
    const QString &text, KFileList *fileList, QProgressDialog &progress)
  {
  QFileInfo info (path + "/" + name);
  if (info.isDir())
    {
    QStringList entries = QDir(path + "/" + name).entryList();
    int l = entries.count();
    for (int i = 0; i < l; i++)
      {
      QString epath = entries[i]; 
      if (epath != "." && epath != ".." && !progress.wasCanceled())
        {
        int v = progress.value();
        v++;
        if (v == 100) v = 0;
        progress.setValue (v);
        if (name == "")
          _doFileSearch (path, epath, text, fileList, progress);
        else
          _doFileSearch (path, name + "/" + epath, text, fileList, progress);
        }
      }
    }
  else
    {
    if (name.contains (text, Qt::CaseInsensitive))
      fileList->addName (name);
    }
  }
Пример #4
0
void Main_Window::on_sweep_clicked()
{
    QProgressDialog *dlg = new QProgressDialog(this);
    dlg->setWindowModality(Qt::WindowModal);
    dlg->setLabelText("Frequency Sweep");
    dlg->setCancelButtonText("Cancel");
    dlg->setMaximum(100);
    dlg->show();
    
    double start = ui.sweep_start->value();
    double stop = ui.sweep_stop->value();
    double step = ui.sweep_step->value();
    
    for (double f = start; f <= stop && !dlg->wasCanceled(); f += step)
    {
        dlg->setValue((int)((f - start) * 100.0 / (stop - start)));
        QCoreApplication::processEvents();
        
        ui.freq->setValue(f);
        on_idle_clicked();
        update_freq();
        send_freq();
        on_cal_clicked();
        on_tx_clicked();
        
        usleep(100 * 1000);
    }
    
    delete dlg;
}
Пример #5
0
void MainWindow::on_actionFind_all_text_string_16_bit_triggered()
{
    HexEditorWidget* v = dynamic_cast<HexEditorWidget*>(ui->twHex->currentWidget());
    if (v==NULL)return;
    QByteArray br = v->data();
    QByteArray akk;
    int lastAdr=0;

    QProgressDialog * progress = new QProgressDialog(tr("Search..."), tr("Cancel"), 0, br.size(), this);
    progress->setWindowModality(Qt::WindowModal);
    progress->show();

    for(int i=0;i<=br.count()-1;i=i+2)
    {
        if (i % 1000 == 0 )
        {
            progress->setValue(i);
            QCoreApplication::processEvents ();
            if (progress->wasCanceled()) break;
        }

        unsigned char c = br[i];
        unsigned char d = br[i+1];

        bool mached = false;

        if( d >= 0x20 && d <= 0x7E && c == 0x00)
        {
            if(akk.count()==0)lastAdr=i;
            akk.append(d);
            mached = true;

        }

        if( d >= 0x20 && d <= 0x7E && c >= 0x20 && c <= 0x7E)
        {
            if(akk.count()==0)lastAdr=i;
            akk.append(d);
            akk.append(c);
            mached = true;

        }

        if(!mached)
        {
            if (akk.length()>3)
            {
                QString s;
                s.setNum(lastAdr,16);
                ui->consoleView->appendPlainText(s.toUpper() + " : \""+akk+"\"");
            }
            akk.clear();
        }
    }

    progress->close();
    delete progress;
}
Пример #6
0
// ///////////////////////SET Doors/////////////////////////////////
void LvlScene::setDoors(QProgressDialog &progress)
{
    int i=0;

    for(i=0; i<LvlData->doors.size(); i++)
    {
        //add Doors points to scene
        placeDoor(LvlData->doors[i]);

        if(progress.wasCanceled())
            //progress.setValue(progress.value()+1);
        /*else*/ return;
    }
}
void updateItemSiteLeadTimes::sUpdate()
{
  ParameterList params;
  _warehouse->appendValue(params);
  _classCode->appendValue(params);

  XSqlQuery updateUpdate;
  QProgressDialog progress;
  progress.setWindowModality(Qt::ApplicationModal);
  
  MetaSQLQuery mql = mqlLoad("updateItemsiteLeadTimes", "load");
  updateUpdate = mql.toQuery(params);
  if (ErrorReporter::error(QtCriticalMsg, this, tr("Error Loading Item Site Lead Times"),
                           updateUpdate, __FILE__, __LINE__))
  {
    return;
  }
  
  int count=0;
  progress.setMaximum(updateUpdate.size());
  XSqlQuery update;
  while (updateUpdate.next())
  {
    progress.setLabelText(tr("Site: %1\n"
                             "Item: %2 - %3")
                          .arg(updateUpdate.value("warehous_code").toString())
                          .arg(updateUpdate.value("item_number").toString())
                          .arg(updateUpdate.value("item_descrip1").toString()));
    
    ParameterList rparams = params;
    rparams.append("itemsite_id", updateUpdate.value("itemsite_id"));
    rparams.append("leadTimePad", _leadTimePad->value());
    MetaSQLQuery mql2 = mqlLoad("updateItemsiteLeadTimes", "update");
    update = mql2.toQuery(rparams);
    if (ErrorReporter::error(QtCriticalMsg, this, tr("Error Updating Item Site Lead Times"),
                             update, __FILE__, __LINE__))
    {
      return;
    }
    
    if (progress.wasCanceled())
      break;
    
    count++;
    progress.setValue(count);
  }

  accept();
}
Пример #8
0
// ///////////////////////SET Waters/////////////////////////////////
void LvlScene::setWaters(QProgressDialog &progress)
{
    int i=0;

    for(i=0; i<LvlData->physez.size(); i++)
    {
        //add Water to scene
        placeWater(LvlData->physez[i]);

        if(progress.wasCanceled())
            //progress.setValue(progress.value()+1);
        /*else*/ return;
    }

}
int CPL_STDCALL QgsImageWarper::updateWarpProgress( double dfComplete, const char *pszMessage, void *pProgressArg )
{
  QProgressDialog *progress = static_cast<QProgressDialog*>( pProgressArg );
  progress->setValue( qMin( 100u, ( uint )( dfComplete*100.0 ) ) );
  qApp->processEvents();
  // TODO: call QEventLoop manually to make "cancel" button more responsive
  if ( progress->wasCanceled() )
  {
    mWarpCanceled = true;
    return false;
  }

  mWarpCanceled = false;
  return true;
}
Пример #10
0
// ///////////////////SET Block Objects/////////////////////////////////////////////
void LvlScene::setBlocks(QProgressDialog &progress)
{
    int i=0;

    //Applay images to objects
    for(i=0; i<LvlData->blocks.size(); i++)
    {
        //Add block to scene
        placeBlock(LvlData->blocks[i]);

        if(progress.wasCanceled())
            //progress.setValue(progress.value()+1);
        /*else*/ return;
    }
}
Пример #11
0
// ///////////////////////SET NonPlayble Characters and Items/////////////////////////////////
void LvlScene::setNPC(QProgressDialog &progress)
{
    int i=0;
    //QGraphicsItem *	box;

    for(i=0; i<LvlData->npc.size(); i++)
    {
        //add NPC to scene
        placeNPC(LvlData->npc[i]);

        if(progress.wasCanceled())
            //progress.setValue(progress.value()+1);
        /*else*/ return;
    }

}
Пример #12
0
void BatchTranslationDialog::startTranslation()
{
    int translatedcount = 0;
    QCursor oldCursor = cursor();
    setCursor(Qt::BusyCursor);
    int messageCount = m_dataModel->messageCount();

    QProgressDialog *dlgProgress;
    dlgProgress = new QProgressDialog(tr("Searching, please wait..."), tr("&Cancel"), 0, messageCount, this);
    dlgProgress->show();

    int msgidx = 0;
    const bool translateTranslated = m_ui.ckTranslateTranslated->isChecked();
    const bool translateFinished = m_ui.ckTranslateFinished->isChecked();
    for (MultiDataModelIterator it(m_dataModel, m_modelIndex); it.isValid(); ++it) {
        if (MessageItem *m = it.current()) {
            if (!m->isObsolete()
                && (translateTranslated || m->translation().isEmpty())
                && (translateFinished || !m->isFinished())) {

                // Go through them in the order the user specified in the phrasebookList
                for (int b = 0; b < m_model.rowCount(); ++b) {
                    QModelIndex idx(m_model.index(b, 0));
                    QVariant checkState = m_model.data(idx, Qt::CheckStateRole);
                    if (checkState == Qt::Checked) {
                        PhraseBook *pb = m_phrasebooks[m_model.data(idx, Qt::UserRole).toInt()];
                        foreach (const Phrase *ph, pb->phrases()) {
                            if (ph->source() == m->text()) {
                                m_dataModel->setTranslation(it, ph->target());
                                m_dataModel->setFinished(it, m_ui.ckMarkFinished->isChecked());
                                ++translatedcount;
                                goto done; // break 2;
                            }
                        }
                    }
                }
            }
        }
      done:
        ++msgidx;
        if (!(msgidx & 15))
            dlgProgress->setValue(msgidx);
        qApp->processEvents();
        if (dlgProgress->wasCanceled())
            break;
    }
Пример #13
0
int QgsRasterFileWriter::pyramidsProgress( double dfComplete, const char *pszMessage, void* pData )
{
  Q_UNUSED( pszMessage );
  GDALTermProgress( dfComplete, 0, 0 );
  QProgressDialog* progressDialog = static_cast<QProgressDialog*>( pData );
  if ( pData && progressDialog->wasCanceled() )
  {
    return 0;
  }

  if ( pData )
  {
    progressDialog->setRange( 0, 100 );
    progressDialog->setValue( dfComplete * 100 );
  }
  return 1;
}
Пример #14
0
// ///////////////////SET BackGround Objects/////////////////////////////////////////////
void LvlScene::setBGO(QProgressDialog &progress)
{
    int i=0;

    //sortBGOArray(FileData.bgo); //Sort BGOs

    //Applay images to objects
    for(i=0; i<LvlData->bgo.size(); i++)
    {
        //add BGO to scene
        placeBGO(LvlData->bgo[i]);

        if(progress.wasCanceled())
            //progress.setValue(progress.value()+1);
        /*else*/ return;
    }

}
void createPlannedOrdersByPlannerCode::sCreate(ParameterList params)
{
  XSqlQuery createCreate;
  QProgressDialog progress;
  progress.setWindowModality(Qt::ApplicationModal);

  MetaSQLQuery mql = mqlLoad("schedule", "load");
  createCreate = mql.toQuery(params);
  if (createCreate.lastError().type() != QSqlError::NoError)
  {
    systemError(this, createCreate.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  int count=0;
  progress.setMaximum(createCreate.size());
  XSqlQuery create;
  while (createCreate.next())
  {
    progress.setLabelText(tr("Site: %1\n"
                             "Item: %2 - %3")
                          .arg(createCreate.value("warehous_code").toString())
                          .arg(createCreate.value("item_number").toString())
                          .arg(createCreate.value("item_descrip1").toString()));

    ParameterList rparams = params;
    rparams.append("itemsite_id", createCreate.value("itemsite_id"));
    MetaSQLQuery mql2 = mqlLoad("schedule", "create");
    create = mql2.toQuery(rparams);
    if (create.lastError().type() != QSqlError::NoError)
    {
      systemError(this, create.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }

    if (progress.wasCanceled())
      break;

    count++;
    progress.setValue(count);
  }

  accept();
}
Пример #16
0
// //////////////////////////Apply used sections///////////////////////////////////////
void LvlScene::makeSectionBG(QProgressDialog &progress)
//void LvlScene::makeSectionBG(int x, int y, int w, int h)
{
    int i, total=0;
    WriteToLog(QtDebugMsg, QString("Applay Backgrounds"));

    //Load Backgrounds
    for(i=0; i<LvlData->sections.size(); i++)
    {
        setSectionBG(LvlData->sections[i]);

        total++;

        if(progress.wasCanceled())
            /*progress.setValue(progress.value()+1);
        else*/ return;
    }

}
Пример #17
0
bool Omr::readPdf()
      {
      QProgressDialog *progress = new QProgressDialog(QWidget::tr("Reading PDF..."), QWidget::tr("Cancel"), 0, 100, 0, Qt::FramelessWindowHint);
      progress->setWindowModality(Qt::ApplicationModal);
      progress->show();
      progress->setRange(0, ACTION_NUM);

#ifdef OCR
      if (_ocr == 0)
            _ocr = new Ocr;
      _ocr->init();
#endif
      int ID = READ_PDF;
      int page = 0;
      bool val;
      while (ID < ACTION_NUM) {
            if(ID != INIT_PAGE && ID != SYSTEM_IDENTIFICATION) {
                  page = 0;
                  progress->setLabelText(QWidget::tr("%1 at Page %2").arg(ActionNames.at(ID+1)).arg(1));
                  val = omrActions(ID, page);
                  }
            else {
                  progress->setLabelText(QWidget::tr("%1 at Page %2").arg(ActionNames.at(ID)).arg(page+1));
                  val = omrActions(ID, page);
                  page++;
                  }

            if (!val || progress->wasCanceled()) {
                  progress->close();
                  return false;
                  }
            else {
                  if (ID < ACTION_NUM)
                        progress->setValue(ID);
                  else
                        progress->setValue(ACTION_NUM - 1);
                  qApp->processEvents();
                  }
            }
      progress->close();
      delete progress;
      return true;
      }
Пример #18
0
void LibraryView::deleteSongs(){
  QSet<library_song_id_t> selectedIds =
    Utils::getSelectedIds<library_song_id_t>(
      this,
      libraryModel,
      DataStore::getLibIdColName(),
      proxyModel);

  QProgressDialog *deletingProgress =
    new QProgressDialog(tr("Deleting Songs..."), tr("Cancel"), 0, selectedIds.size()*2, this);
  deletingProgress->setWindowModality(Qt::WindowModal);
  deletingProgress->setMinimumDuration(250);

  dataStore->removeSongsFromLibrary(selectedIds, deletingProgress);
  if(!deletingProgress->wasCanceled()){
    emit libNeedsSync();
  }
  deletingProgress->close();
}
Пример #19
0
void MetaWindow::addMediaSources(const QList<Phonon::MediaSource>& musicToAdd){
  if(musicToAdd.isEmpty()){
    QMessageBox::information(
        this, 
        "No Music Found", 
        "Sorry, but we couldn't find any new music that we know how to play.");
    return;
  }

  int numNewFiles = musicToAdd.size();
  QProgressDialog *addingProgress = new QProgressDialog(
    "Loading Library...", "Cancel", 0, numNewFiles, this);
  addingProgress->setWindowModality(Qt::WindowModal);
  addingProgress->setMinimumDuration(250);
  dataStore->addMusicToLibrary(musicToAdd, addingProgress);
  if(!addingProgress->wasCanceled()){
    syncLibrary();
  }
  addingProgress->close();
}
// ///////////////////////SET NonPlayble Characters and Items/////////////////////////////////
void LvlScene::setNPC(QProgressDialog &progress)
{
    int i=0;
    //QGraphicsItem *	box;

    for(i=0; i<m_data->npc.size(); i++)
    {
        LevelNPC &npc = m_data->npc[i];
        //add NPC to scene
        ItemNPC *n = placeNPC(npc);
        //FIXME: TEMPORARY, Remove this after removing of real-time PGE-FL <-> Scene synchronization
        Q_ASSERT(n);
        npc.contents        = n->m_data.contents;
        npc.special_data    = n->m_data.special_data;
        //------------------------------------------------------------------------------------------

        qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
        if(progress.wasCanceled())
            return;
    }

}
Пример #21
0
bool KDReports::ReportPrivate::doPrint( QPrinter* printer, QWidget* parent )
{
    // caller has to ensure that we have been layouted for this printer already
    const int pageCount = m_layout->numberOfPages();
    QProgressDialog* dialog = 0;
    if ( QThread::currentThread() == qApp->thread() ) {
        dialog = new QProgressDialog( QObject::tr( "Printing" ), QObject::tr( "Cancel" ), 0, pageCount, parent );
        dialog->setWindowModality( Qt::ApplicationModal );
    }
    QPainter painter( printer );

    int fromPage = 0;
    int toPage = pageCount;
    if ( printer->printRange() == QPrinter::PageRange ) {
        fromPage = printer->fromPage() - 1; // it starts at 1
        toPage = printer->toPage(); // -1 because it starts at 1, and +1 because of '<'
        if ( toPage == 0 )
            toPage = pageCount;
    }

    bool firstPage = true;
    for ( int pageIndex = fromPage; pageIndex < toPage; ++pageIndex ) {
        if ( dialog ) {
            dialog->setValue( pageIndex );
            if ( dialog->wasCanceled() )
                break;
        }

        if ( !firstPage )
            printer->newPage();

        paintPage( pageIndex, painter );
        firstPage = false;
    }

    delete dialog;
    return true;
}
Пример #22
0
void Segments::makeSegments(QImage &imageProcessed, SegmentSettings seg)
{
    segments.clear(); // autoDelete is on

    // statistics that show up in debug spew
    int madeLines = 0;
    int shortLines = 0; // lines rejected since their segments are too short
    int foldedLines = 0; // lines rejected since they could be into other lines

    // debugging with modal progress dialog box is problematic so make switchable
    const bool useDlg = true;

    // for each new column of pixels, loop through the runs. a run is defined as
    // one or more colored pixels that are all touching, with one uncolored pixel or the
    // image boundary at each end of the set. for each set in the current column, count
    // the number of runs it touches in the adjacent (left and right) columns. here is
    // the pseudocode:
    //   if ((L > 1) || (R > 1))
    //     "this run is at a branch point so ignore the set"
    //   else
    //     if (L == 0)
    //       "this run is the start of a new segment"
    //     else
    //       "this run is appended to the segment on the left
    int width = imageProcessed.width();
    int height = imageProcessed.height();

    QProgressDialog* dlg;
    if (useDlg)
    {

        dlg = new QProgressDialog("Scanning segments in image", "Cancel", 0, width);
        CHECK_PTR_ENGAUGE(dlg);
        dlg->setCaption(QString("Progress"));
        dlg->show();
    }

    bool* lastBool = new bool [height];
    CHECK_PTR_ENGAUGE(lastBool);
    bool* currBool = new bool [height];
    CHECK_PTR_ENGAUGE(currBool);
    bool* nextBool = new bool [height];
    CHECK_PTR_ENGAUGE(nextBool);
    Segment** lastSegment = new Segment* [height];
    CHECK_PTR_ENGAUGE(lastSegment);
    Segment** currSegment = new Segment* [height];
    CHECK_PTR_ENGAUGE(currSegment);

    Discretize discretize;
    loadBool(&discretize, lastBool, &imageProcessed, -1);
    loadBool(&discretize, currBool, &imageProcessed, 0);
    loadBool(&discretize, nextBool, &imageProcessed, 1);
    loadSegment(lastSegment, height);

    for (int x = 0; x < width; x++)
    {
        if (useDlg)
        {
            // update progress bar
            dlg->setValue(x);
            qApp->processEvents();

            if (dlg->wasCanceled())
                // quit scanning. only existing segments will be available
                break;
        }

        matchRunsToSegments(x, height, lastBool, lastSegment, currBool, currSegment, nextBool, seg,
                            &madeLines, &foldedLines, &shortLines);

        // get ready for next column
        scrollBool(lastBool, currBool, height);
        scrollBool(currBool, nextBool, height);
        if (x + 1 < width)
            loadBool(&discretize, nextBool, &imageProcessed, x + 1);
        scrollSegment(lastSegment, currSegment, height);
    }

    if (useDlg)
    {
        dlg->setValue(width);
        delete dlg;
    }

    DigitDebug::scanning(QString("segment lines created ") + QString::number(madeLines) +
                         QString(", too short so removed ") + QString::number(shortLines) +
                         QString(", folded together ") + QString::number(foldedLines));

    delete[] lastBool;
    delete[] currBool;
    delete[] nextBool;
    delete[] lastSegment;
    delete[] currSegment;
}
Пример #23
0
int QgsGridFileWriter::writeFile( bool showProgressDialog )
{
  QFile outputFile( mOutputFilePath );

  if ( !outputFile.open( QFile::WriteOnly ) )
  {
    return 1;
  }

  if ( !mInterpolator )
  {
    outputFile.remove();
    return 2;
  }

  QTextStream outStream( &outputFile );
  outStream.setRealNumberPrecision( 8 );
  writeHeader( outStream );

  double currentYValue = mInterpolationExtent.yMaximum() - mCellSizeY / 2.0; //calculate value in the center of the cell
  double currentXValue;
  double interpolatedValue;

  QProgressDialog* progressDialog = 0;
  if ( showProgressDialog )
  {
    progressDialog = new QProgressDialog( QObject::tr( "Interpolating..." ), QObject::tr( "Abort" ), 0, mNumRows, 0 );
    progressDialog->setWindowModality( Qt::WindowModal );
  }

  for ( int i = 0; i < mNumRows; ++i )
  {
    currentXValue = mInterpolationExtent.xMinimum() + mCellSizeX / 2.0; //calculate value in the center of the cell
    for ( int j = 0; j < mNumColumns; ++j )
    {
      if ( mInterpolator->interpolatePoint( currentXValue, currentYValue, interpolatedValue ) == 0 )
      {
        outStream << interpolatedValue << " ";
      }
      else
      {
        outStream << "-9999 ";
      }
      currentXValue += mCellSizeX;
    }
    outStream << endl;
    currentYValue -= mCellSizeY;

    if ( showProgressDialog )
    {
      if ( progressDialog->wasCanceled() )
      {
        outputFile.remove();
        return 3;
      }
      progressDialog->setValue( i );
    }
  }

  delete progressDialog;
  return 0;
}
Пример #24
0
void MainWindow::importFile()
{
    QFile loadfile(filename);
    loadfile.open(QIODevice::ReadOnly);
    QDataStream ls(&loadfile);
    ls.setByteOrder(QDataStream::BigEndian);
    ls.device()->seek(3200);
    Reel.ReadREEL(ls);

    //Max_XLine=Max_YLine=Min_XLine=Min_YLine=0;

    DBTrace t;


    int xLine;               //主测线号XLINE
    int oldxLine;
    int inLine;              //inLine 号
    int temp,_temp,N;
    temp =_temp=0;
    N=0;

    QFile writefile(filename+tr("_db"));
    writefile.open(QIODevice::WriteOnly);
    QDataStream ws(&writefile);
    QProgressDialog *pdg = new QProgressDialog(this);
    QFont font("Times",10,QFont::Bold);
    pdg->setFont(font);
    pdg->setWindowModality(Qt::WindowModal);
    pdg->setWindowTitle(tr("导入SEGY文件"));
    pdg->setLabelText(tr("扫描SEGY数据"));
    pdg->setCancelButtonText(tr("取消"));
    pdg->setRange(0,Reel.TotalTraces);
    pdg->setMinimumDuration(500);
    int HNS = Reel.hns;
    int DataType = Reel.DataType;
    xLine = oldxLine = 0;
    pdg->setValue(0);
    qApp->processEvents();

    for( int i = 0; i < Reel.TotalTraces; i ++)
    {
        double fp =  3600.0 + 8.0 + double(i)*double(HNS*DataType + 240.0);
        pdg->setValue(i+1);
        qApp->processEvents();
        if (pdg->wasCanceled())
        {
            break;
        }
        ws<<i;
        ls.device()->seek(fp);
        ls >>xLine;
        ls.device()->seek(fp+12.0);
        ls>>inLine;

        t.fp = i;
        t.in = xLine;
        t.cross = inLine;
        t.st = 0;
        t.et = Reel.hns*Reel.hdt/1000;
        CdbTrace->AddData(t);

        if( i == 0 )
        {
            Max_XLine = xLine;
            Min_XLine = xLine;
            Max_YLine = inLine;
            Min_YLine = inLine;
        }
        else
        {
            if( xLine > Max_XLine )
                Max_XLine = xLine;
            if( xLine < Min_XLine )
                Min_XLine = xLine;
            if( inLine > Max_YLine )
                Max_YLine = inLine;
            if( inLine < Min_YLine )
                Min_YLine = inLine;
        }

    }

    loadfile.close();


    /**/
    reelAction->setEnabled(true);
    traceAction->setEnabled(true);
    dataAction->setEnabled(true);
}
Пример #25
0
bool CSVToolWindow::importStart()
{
  QString mapname = atlasWindow()->map();
  CSVAtlas *atlas = _atlasWindow->getAtlas();

  if (mapname.isEmpty())
  {
    QStringList mList = atlas->mapList();

    if(mList.isEmpty())
    {
      _msghandler->message(QtWarningMsg, tr("No Maps Loaded"),
                           tr("<p>There are no maps loaded to select from. "
                              "Either load an atlas that contains maps or "
                              "create a new one before continuing."));
      return false;
    }

    mList.sort();
    bool valid;
    mapname = QInputDialog::getItem(this, tr("Select Map"), tr("Select Map:"),
                                    mList, 0, false, &valid);
    if (!valid)
      return false;
  }

  CSVMap map = atlas->map(mapname);
  map.simplify();
  QList<CSVMapField> fields = map.fields();

  if (map.name() != mapname || fields.isEmpty())
  {
    _msghandler->message(QtWarningMsg, tr("Invalid Map"),
                         tr("<p>The selected map does not appear to be valid."));
    return false;
  }

  CSVMap::Action action = map.action();
  if (action != CSVMap::Insert)
  {
    _msghandler->message(QtWarningMsg, tr("Action not implemented"),
                         tr("<p>The action %1 for this map is not supported.")
                         .arg(CSVMap::actionToName(action)));
    return false;
  }

  if (!_data || _data->rows() < 1)
  {
    _msghandler->message(QtWarningMsg, tr("No data"),
                         tr("<p>There are no data to process. "
                            "Load a CSV file before continuing."));
    return false;
  }

  int total = _data->rows();
  int current = 0, error = 0, ignored = 0;

  if (! _log)
    _log = new LogWindow(this);

  if(usetransaction) QSqlQuery begin("BEGIN;");

  QString errMsg;
  if(!map.sqlPre().trimmed().isEmpty())
  {
    if(usetransaction) QSqlQuery savepoint("SAVEPOINT presql;");
    QSqlQuery pre;
    if(!pre.exec(map.sqlPre()))
    {
      errMsg = QString("ERROR Running Pre SQL query: %1").arg(pre.lastError().text());
      _log->_log->append("\n\n----------------------\n");
      _log->_log->append(errMsg);
      _log->show();
      _log->raise();
      if(map.sqlPreContinueOnError())
      {
        _log->_log->append(tr("\n\nContinuing with rest of import\n\n"));
        if(usetransaction) QSqlQuery sprollback("ROLLBACK TO SAVEPOINT presql;");
        if(usetransaction) QSqlQuery savepoint("RELEASE SAVEPOINT presql;");
      }
      else
      {
        if(usetransaction) QSqlQuery rollback("ROLLBACK;");
        _msghandler->message(QtWarningMsg, tr("Error"),
                             tr("<p>There was an error running the Pre SQL "
                                "query. "
                                "Aborting transaction."
                                "\n\n----------------------\n%1").arg(errMsg));
        return false;
      }
    }
  }

  QString progresstext(tr("Importing %1: %2 rows out of %3"));
  int expected = total;
  QProgressDialog *progress = new QProgressDialog(progresstext
                                        .arg(map.name()).arg(0).arg(expected),
                                        tr("Cancel"), 0, expected, this);
  progress->setWindowModality(Qt::WindowModal);
  bool userCanceled = false;

  QString query;
  QString front;
  QString back;
  QString value;
  QString label;
  QVariant var;

  QStringList errorList;

  for(current = 0; current < total; ++current)
  {
    if(usetransaction) QSqlQuery savepoint("SAVEPOINT csvinsert;");
    if(action == CSVMap::Insert)
    {
      query = QString("INSERT INTO %1 ").arg(map.table());
      front = "(";
      back = " VALUES(";
      QList<CSVMapField> fields = map.fields();
      QMap<QString,QVariant> values;
      for (int i = 0; i < fields.size(); i++)
      {
        switch(fields.at(i).action())
        {
          case CSVMapField::Action_UseColumn:
          {
            value = _data->value(current, fields.at(i).column()-1);
            if(value.isNull())
            {
              switch (fields.at(i).ifNullAction())
              {
                case CSVMapField::UseDefault:
                  continue;
                case CSVMapField::UseEmptyString:
                {
                  var = QVariant(QString(""));
                  break;
                }
                case CSVMapField::UseAlternateValue:
                {
                  var = QVariant(fields.at(i).valueAlt());
                  break;
                }
                case CSVMapField::UseAlternateColumn:
                {
                  value = _data->value(current, fields.at(i).columnAlt()-1);
                  if(value.isNull())
                  {
                    switch (fields.at(i).ifNullActionAlt())
                    {
                      case CSVMapField::UseDefault:
                        continue;
                      case CSVMapField::UseEmptyString:
                      {
                        var = QVariant(QString(""));
                        break;
                      }
                      case CSVMapField::UseAlternateValue:
                      {
                        var = QVariant(fields.at(i).valueAlt());
                        break;
                      }
                      default: // Nothing
                        var = QVariant(QString::null);
                    }
                  }
                  else
                    var = QVariant(value);
                  break;
                }
                default: // Nothing
                  var = QVariant(QString::null);
              }
            }
            else
              var = QVariant(value);
            break;
          }
          case CSVMapField::Action_UseEmptyString:
          {
            var = QVariant(QString(""));
            break;
          }
          case CSVMapField::Action_UseAlternateValue:
          {
            var = QVariant(fields.at(i).valueAlt());
            break;
          }
          case CSVMapField::Action_UseNull:
          {
            var = QVariant(QString::null);
            break;
          }
          default:
            continue;
        }

        label = ":" + fields.at(i).name();
        if(!values.empty())
        {
          front += ", ";
          back  += ", ";
        }
        values.insert(label, var);
        front += fields.at(i).name();
        back  += label;
      }

      if(values.empty())
      {
        ignored++;
        errMsg = QString("IGNORED Record %1: There are no columns to insert").arg(current+1);
        errorList.append(errMsg);
        continue;
      }

      front += ") ";
      back += ")";
      query += front + back;
      QSqlQuery qry;
      qry.prepare(query);

      QMap<QString,QVariant>::iterator vit;
      for(vit = values.begin(); vit != values.end(); ++vit)
        qry.bindValue(vit.key(), vit.value());

      if(!qry.exec())
      {
        if(usetransaction) QSqlQuery sprollback("ROLLBACK TO SAVEPOINT csvinsert;");
        error++;
        errMsg = QString("ERROR Record %1: %2").arg(current+1).arg(qry.lastError().text());
        errorList.append(errMsg);
      }
    }
    if (progress->wasCanceled())
    {
      userCanceled = true;
      break;
    }
    if(! (current % 1000))
    {
      progress->setLabelText(progresstext.arg(map.name()).arg(current).arg(expected));
      progress->setValue(current);
    }
  }
  progress->setValue(total);

  if (error || ignored || userCanceled)
  {
    _log->_log->append(tr("Map: %1\n"
                          "Table: %2\n"
                          "Method: %3\n\n"
                          "Total Records: %4\n"
                          "# Processed:   %5\n"
                          "# Ignored:     %6\n"
                          "# Errors:      %7\n\n")
                          .arg(map.name()).arg(map.table())
                          .arg(CSVMap::actionToName(map.action()))
                          .arg(total).arg(current).arg(ignored).arg(error));
    _log->_log->append(errMsg);
    _log->_log->append(errorList.join("\n"));
    _log->show();
    _log->raise();
    if (_msghandler &&  // log messages there's a non-interactive message handler
        qobject_cast<XAbstractMessageHandler*>(_msghandler) &&
        ! qobject_cast<InteractiveMessageHandler*>(_msghandler))
      _msghandler->message(error ? QtCriticalMsg : QtWarningMsg,
                           tr("Import Processing Status"),
                           _log->_log->toPlainText());
  }

  if (! userCanceled && ! map.sqlPost().trimmed().isEmpty())
  {
    QSqlQuery post;
    if(!post.exec(map.sqlPost()))
    {
      errMsg = QString("ERROR Running Post SQL query: %1").arg(post.lastError().text());
      _log->_log->append("\n\n----------------------\n");
      _log->_log->append(errMsg);
      _log->show();
      _log->raise();
      if(usetransaction) QSqlQuery rollback("ROLLBACK;");
      _msghandler->message(QtCriticalMsg, tr("Error"),
                           tr("<p>There was an error running the post sql "
                              "query and changes were rolled back. "
                              "\n\n----------------------\n%1").arg(errMsg));
      return false;
    }
  }

  if (userCanceled)
  {
    if(usetransaction) QSqlQuery rollback("ROLLBACK;");
    _log->_log->append(tr("\n\nImport canceled by user. Changes were rolled back."));

    return false;
  }

  if(usetransaction) QSqlQuery commit("COMMIT");
  if (! error)
  {
    _msghandler->message(QtDebugMsg, tr("Import Complete"),
                         tr("The import of %1 completed successfully.")
                         .arg(_currentDir));
    return true;
  }

  return false;
}
Пример #26
0
void LvlScene::loadUserData(QProgressDialog &progress)
{
    int i, total=0;

    UserBGs uBG;
    UserBlocks uBlock;
    UserBGOs uBGO;
    UserNPCs uNPC;

    bool WrongImagesDetected=false;

    uBGOs.clear();
    uBlocks.clear();
    uNPCs.clear();
    uBGs.clear();

    bool loaded1, loaded2;
    QString uLVLDs = LvlData->path + "/" + LvlData->filename + "/";
    QString uLVLD = LvlData->path + "/" + LvlData->filename;
    QString uLVLs = LvlData->path + "/";


    if(!progress.wasCanceled())
        progress.setLabelText(
                    tr("Search User Backgrounds %1")
                    .arg(QString::number(pConfigs->main_bg.size()) ) );

    qApp->processEvents();
    //Load Backgrounds
    for(i=0; i<pConfigs->main_bg.size(); i++) //Add user images
        {
            loaded1 = false;
            loaded2 = false;

            //check for first image
            if((QFile::exists(uLVLD) ) &&
                  (QFile::exists(uLVLDs + pConfigs->main_bg[i].image_n)) )
            {
                uBG.image = GraphicsHelps::loadPixmap( uLVLDs + pConfigs->main_bg[i].image_n );
                uBG.id = pConfigs->main_bg[i].id;
                if(uBG.image.isNull()) WrongImagesDetected=true;
                loaded1 = true;
            }
            else
            if(QFile::exists(uLVLs + pConfigs->main_bg[i].image_n) )
            {
                uBG.image = GraphicsHelps::loadPixmap( uLVLs + pConfigs->main_bg[i].image_n );
                uBG.id = pConfigs->main_bg[i].id;
                if(uBG.image.isNull()) WrongImagesDetected=true;
                loaded1 = true;
            }

            if((loaded1)&&(pConfigs->main_bg[i].animated) )
            {
                uBG.image=uBG.image.copy(0, 0, uBG.image.width(), (int)round(uBG.image.height()/pConfigs->main_bg[i].frames));
            }

            //check for second image
            if(pConfigs->main_bg[i].type == 1)
            {
                if((QFile::exists(uLVLD) ) &&
                      (QFile::exists(uLVLDs + pConfigs->main_bg[i].second_image_n )) )
                {
                    uBG.second_image = GraphicsHelps::loadPixmap( uLVLDs + pConfigs->main_bg[i].second_image_n );
                    uBG.id = pConfigs->main_bg[i].id;
                    loaded2 = true;
                    if(uBG.second_image.isNull()) WrongImagesDetected=true;
                }
                else
                if(QFile::exists(uLVLs + pConfigs->main_bg[i].second_image_n) )
                {
                    uBG.second_image = GraphicsHelps::loadPixmap( uLVLs + pConfigs->main_bg[i].second_image_n );
                    uBG.id = pConfigs->main_bg[i].id;
                    loaded2 = true;
                    if(uBG.second_image.isNull()) WrongImagesDetected=true;
                }
            }
            if((loaded1)&&(!loaded2)) uBG.q = 0;
            if((!loaded1)&&(loaded2)) uBG.q = 1;
            if((loaded1)&&(loaded2)) uBG.q = 2;


            //If user images found and loaded
            if( (loaded1) || (loaded2) )
                uBGs.push_back(uBG);

        total++;
        if(progress.wasCanceled())
            /*progress.setValue(progress.value()+1);
        else*/ return;
        }

///////////////////////////////////////////////////////////////////////////

    if(!progress.wasCanceled())
    {
        progress.setLabelText(
                    tr("Search User Blocks %1")
                    .arg(QString::number(pConfigs->main_block.size()) ) );
        progress.setValue(progress.value()+1);
    }
    qApp->processEvents();
    //Load Blocks
    for(i=0; i<pConfigs->main_block.size(); i++) //Add user images
    {

        bool custom=false;

            if((QFile::exists(uLVLD) ) &&
                  (QFile::exists(uLVLDs + pConfigs->main_block[i].image_n)) )
            {
                if(QFile::exists(uLVLDs + pConfigs->main_block[i].mask_n))
                    uBlock.mask = GraphicsHelps::loadPixmap( uLVLDs + pConfigs->main_block[i].mask_n );
                else
                    uBlock.mask = pConfigs->main_block[i].mask;

                uBlock.image = GraphicsHelps::setAlphaMask(GraphicsHelps::loadPixmap(uLVLDs + pConfigs->main_block[i].image_n ), uBlock.mask);
                if(uBlock.image.isNull()) WrongImagesDetected=true;

                uBlock.id = pConfigs->main_block[i].id;
                uBlocks.push_back(uBlock);
                custom=true;

                //Apply index;
                if(uBlock.id < (unsigned int)index_blocks.size())
                {
                    index_blocks[uBlock.id].type = 1;
                    //index_blocks[uBlock.id].i = (uBlocks.size()-1);
                }
            }
            else
            if(QFile::exists(uLVLs + pConfigs->main_block[i].image_n) )
            {
                if(QFile::exists(uLVLs + pConfigs->main_block[i].mask_n))
                    uBlock.mask = GraphicsHelps::loadPixmap(uLVLs + pConfigs->main_block[i].mask_n );
                else
                    uBlock.mask = pConfigs->main_block[i].mask;

                uBlock.image = GraphicsHelps::setAlphaMask(GraphicsHelps::loadPixmap(uLVLs + pConfigs->main_block[i].image_n ), uBlock.mask);
                if(uBlock.image.isNull()) WrongImagesDetected=true;

                uBlock.id = pConfigs->main_block[i].id;
                uBlocks.push_back(uBlock);
                custom=true;

                //Apply index;
                if(uBlock.id < (unsigned int)index_blocks.size())
                {
                    index_blocks[uBlock.id].type = 1;
                    //index_blocks[uBlock.id].i = (uBlocks.size()-1);
                }
            }


            int frameFirst;
            int frameLast;

            switch(pConfigs->main_block[i].algorithm)
            {
                case 1: // Invisible block
                {
                    frameFirst = 5;
                    frameLast = 6;
                    break;
                }
                case 3: //Player's character block
                {
                    frameFirst = 0;
                    frameLast = 1;
                    break;
                }
                case 4: //Player's character switch
                {
                    frameFirst = 0;
                    frameLast = 3;
                    break;
                }
                default: //Default block
                {
                    frameFirst = 0;
                    frameLast = -1;
                    break;
                }
            }
            SimpleAnimator * aniBlock = new SimpleAnimator(
                        ((custom)?
                             ((uBlocks.last().image.isNull())?
                                uBgoImg:
                                    uBlocks.last().image)
                                 :
                             ((pConfigs->main_block[i].image.isNull())?
                                uBgoImg:
                                   pConfigs->main_block[i].image)
                             ),
                                  pConfigs->main_block[i].animated,
                                  pConfigs->main_block[i].frames,
                                  pConfigs->main_block[i].framespeed, frameFirst,frameLast,
                                  pConfigs->main_block[i].animation_rev,
                                  pConfigs->main_block[i].animation_bid
                                  );

            animates_Blocks.push_back( aniBlock );
            index_blocks[pConfigs->main_block[i].id].i = i;
            index_blocks[pConfigs->main_block[i].id].ai = animates_Blocks.size()-1;

            #ifdef _DEBUG_
                WriteToLog(QtDebugMsg, QString("BGO Animator ID: %1").arg(index_bgo[pConfigs->main_bgo[i].id].ai));
            #endif

    if(progress.wasCanceled())
        /*progress.setValue(progress.value()+1);
    else*/ return;
    }

///////////////////////////////////////////////////////////////////////////

    if(!progress.wasCanceled())
    {
        progress.setLabelText(
                    tr("Search User BGOs %1")
                    .arg(QString::number(pConfigs->main_bgo.size()) ) );

        progress.setValue(progress.value()+1);
    }
    qApp->processEvents();
    //Load BGO
    for(i=0; i<pConfigs->main_bgo.size(); i++) //Add user images
    {

        bool custom=false;
            if((QFile::exists(uLVLD) ) &&
                  (QFile::exists(uLVLDs + pConfigs->main_bgo[i].image_n)) )
            {
                if(QFile::exists(uLVLDs + pConfigs->main_bgo[i].mask_n))
                    uBGO.mask = GraphicsHelps::loadPixmap(uLVLDs + pConfigs->main_bgo[i].mask_n );
                else
                    uBGO.mask = pConfigs->main_bgo[i].mask;

                uBGO.image = GraphicsHelps::setAlphaMask(GraphicsHelps::loadPixmap(uLVLDs + pConfigs->main_bgo[i].image_n ), uBGO.mask);
                if(uBGO.image.isNull()) WrongImagesDetected=true;

                uBGO.id = pConfigs->main_bgo[i].id;
                uBGOs.push_back(uBGO);
                custom=true;

                //Apply index;
                if(uBGO.id < (unsigned int)index_bgo.size())
                {
                    index_bgo[uBGO.id].type = 1;
                    index_bgo[uBGO.id].i = (uBGOs.size()-1);
                }
            }
            else
            if(QFile::exists(uLVLs + pConfigs->main_bgo[i].image_n) )
            {
                if(QFile::exists(uLVLs + pConfigs->main_bgo[i].mask_n))
                    uBGO.mask = GraphicsHelps::loadPixmap(uLVLs + pConfigs->main_bgo[i].mask_n );
                else
                    uBGO.mask = pConfigs->main_bgo[i].mask;

                uBGO.image = GraphicsHelps::setAlphaMask(GraphicsHelps::loadPixmap(uLVLs + pConfigs->main_bgo[i].image_n ), uBGO.mask);
                if(uBGO.image.isNull()) WrongImagesDetected=true;

                uBGO.id = pConfigs->main_bgo[i].id;
                uBGOs.push_back(uBGO);
                custom=true;

                //Apply index;
                if(uBGO.id < (unsigned int)index_bgo.size())
                {
                    index_bgo[uBGO.id].type = 1;
                    //index_bgo[uBGO.id].i = (uBGOs.size()-1);
                }
            }


            SimpleAnimator * aniBGO = new SimpleAnimator(
                        ((custom)?
                             ((uBGOs.last().image.isNull())?
                                uBgoImg:
                                    uBGOs.last().image)
                                 :
                             ((pConfigs->main_bgo[i].image.isNull())?
                                uBgoImg:
                                   pConfigs->main_bgo[i].image)
                             ),
                                  pConfigs->main_bgo[i].animated,
                                  pConfigs->main_bgo[i].frames,
                                  pConfigs->main_bgo[i].framespeed
                                  );
            animates_BGO.push_back( aniBGO );
            index_bgo[pConfigs->main_bgo[i].id].i = i;
            index_bgo[pConfigs->main_bgo[i].id].ai = animates_BGO.size()-1;
            #ifdef _DEBUG_
                WriteToLog(QtDebugMsg, QString("BGO Animator ID: %1").arg(index_bgo[pConfigs->main_bgo[i].id].ai));
            #endif

        if(progress.wasCanceled())
            /*progress.setValue(progress.value()+1);
        else*/ return;
    }

///////////////////////////////////////////////////////////////////////////


    if(!progress.wasCanceled())
    {
        progress.setLabelText(
                    tr("Search User NPCs %1")
                    .arg(QString::number(pConfigs->main_npc.size()) ) );

        progress.setValue(progress.value()+1);
    }
    qApp->processEvents();

    //Load NPC
    for(i=0; i<pConfigs->main_npc.size(); i++) //Add user images
    {
        if(!progress.wasCanceled())
            progress.setLabelText(
                        tr("Search User NPCs %1")
                        .arg(QString::number(i+1)+"/"+QString::number(pConfigs->main_npc.size()) ) );

             uNPC.withImg = false;
             uNPC.withTxt = false;

             QSize capturedS = QSize(0,0);

             // /////////////////////// Looking for user's NPC.txt ////////////////////////////
             // //(for use custom image filename, need to parse NPC.txt before iamges)/////////
             if((QFile::exists(uLVLD) ) &&
                   (QFile::exists(uLVLDs +
                      "npc-" + QString::number(pConfigs->main_npc[i].id)+".txt") ) )
             {
                QFile file(uLVLDs +
                           "npc-" + QString::number(pConfigs->main_npc[i].id)+".txt");
                if(file.open(QIODevice::ReadOnly))
                {
                    uNPC.sets = FileFormats::ReadNpcTXTFile(file, true);
                    uNPC.id = pConfigs->main_npc[i].id;
                    uNPC.withTxt = true;
                }
             }
             else
             if(QFile::exists(uLVLs +
                              "npc-" + QString::number(pConfigs->main_npc[i].id)+".txt"
                              ) )
             {
                 QFile file(uLVLs +
                            "npc-" + QString::number(pConfigs->main_npc[i].id)+".txt");
                 if(file.open(QIODevice::ReadOnly))
                 {
                     uNPC.sets = FileFormats::ReadNpcTXTFile(file, true);
                     uNPC.id = pConfigs->main_npc[i].id;
                     uNPC.withTxt = true;
                 }
             }

             // ///////////////////////Looking for user's GFX
             if((QFile::exists(uLVLD) ) &&
                   (QFile::exists(uLVLDs + pConfigs->main_npc[i].image_n)) )
             {
                 if(QFile::exists(uLVLDs + pConfigs->main_npc[i].mask_n))
                     uNPC.mask = GraphicsHelps::loadPixmap(uLVLDs + pConfigs->main_npc[i].mask_n );
                 else
                     uNPC.mask = pConfigs->main_npc[i].mask;

                 uNPC.image = GraphicsHelps::setAlphaMask(GraphicsHelps::loadPixmap(uLVLDs + pConfigs->main_npc[i].image_n ), uNPC.mask);
                 if(uNPC.image.isNull()) WrongImagesDetected=true;

                 uNPC.id = pConfigs->main_npc[i].id;
                 uNPC.withImg = true;
             }
             else
             if(QFile::exists(uLVLs + pConfigs->main_npc[i].image_n) )
             {
                 if(QFile::exists(uLVLs + pConfigs->main_npc[i].mask_n))
                     uNPC.mask = GraphicsHelps::loadPixmap(uLVLs + pConfigs->main_npc[i].mask_n );
                 else
                     uNPC.mask = pConfigs->main_npc[i].mask;

                 uNPC.image = GraphicsHelps::setAlphaMask(GraphicsHelps::loadPixmap(uLVLs + pConfigs->main_npc[i].image_n ), uNPC.mask);
                 if(uNPC.image.isNull()) WrongImagesDetected=true;

                 uNPC.id = pConfigs->main_npc[i].id;
                 uNPC.withImg = true;
             }

             if(uNPC.withImg)
             {
                 capturedS = QSize(uNPC.image.width(), uNPC.image.height());
             }

             if(uNPC.withTxt)
             {  //Merge global and user's settings from NPC.txt file
                 uNPC.merged = FileFormats::mergeNPCConfigs(pConfigs->main_npc[i], uNPC.sets, capturedS);
             }
             else
             {
                 if(uNPC.withImg)
                 {
                     NPCConfigFile autoConf = FileFormats::CreateEmpytNpcTXTArray();

                     autoConf.gfxwidth = capturedS.width();
                     //autoConf.en_gfxwidth = true;
                     unsigned int defGFX_h;
                     switch(pConfigs->main_npc[i].framestyle)
                     {
                     case 0:
                         defGFX_h = (int)round(capturedS.height() / pConfigs->main_npc[i].frames);
                         break;
                     case 1:
                         defGFX_h = (int)round((capturedS.height() / pConfigs->main_npc[i].frames)/2 );
                         break;
                     case 2:
                         defGFX_h = (int)round((capturedS.height()/pConfigs->main_npc[i].frames)/4);
                         break;
                     case 3:
                         defGFX_h = (int)round((capturedS.height()/pConfigs->main_npc[i].frames)/4);
                         break;
                     case 4:
                         defGFX_h = (int)round((capturedS.height()/pConfigs->main_npc[i].frames)/8);
                         break;
                     default:
                         defGFX_h=0;
                         break;
                     }

                     capturedS.setHeight(defGFX_h);

                     uNPC.merged = FileFormats::mergeNPCConfigs(
                                 pConfigs->main_npc[i],
                                 autoConf, capturedS);
                 }

             }

             //Apply only if custom config or image was found
             if((uNPC.withImg)||(uNPC.withTxt))
             {
                 uNPCs.push_back(uNPC);
                 //Apply index;
                 if(uNPC.id < (unsigned int)index_npc.size())
                 {
                     index_npc[uNPC.id].type = 1;
                     index_npc[uNPC.id].i = (uNPCs.size()-1);
                 }
             }
         if(progress.wasCanceled())
             /*progress.setValue(progress.value()+1);
         else*/ return;
     }

    progress.setValue(progress.value()+1);
    qApp->processEvents();

    //Notification about wrong custom image sprites
    if(WrongImagesDetected)
    {
        QMessageBox * msg = new QMessageBox();
        msg->setWindowFlags(msg->windowFlags() | Qt::WindowStaysOnTopHint);
        msg->setWindowTitle(tr("Wrong custom images"));
        msg->setText(tr("This level have a wrong custom graphics files.\nYou will see 'ghosties' or other dummy images instead custom GFX of items, what used broken images. It occurred because, for example, the BMP format with GIF extension was used.\nPlease, reconvert your images to valid format and try to reload this level."));
        msg->addButton(QMessageBox::Ok);
        msg->setIcon(QMessageBox::Warning);

        msg->exec();
    }
}
Пример #27
0
void QgsTINInterpolator::initialize()
{
  DualEdgeTriangulation* theDualEdgeTriangulation = new DualEdgeTriangulation( 100000, 0 );
  if ( mInterpolation == CloughTocher )
  {
    NormVecDecorator* dec = new NormVecDecorator();
    dec->addTriangulation( theDualEdgeTriangulation );
    mTriangulation = dec;
  }
  else
  {
    mTriangulation = theDualEdgeTriangulation;
  }

  //get number of features if we use a progress bar
  int nFeatures = 0;
  int nProcessedFeatures = 0;
  if ( mShowProgressDialog )
  {
    QList<LayerData>::iterator layerDataIt = mLayerData.begin();
    for ( ; layerDataIt != mLayerData.end(); ++layerDataIt )
    {
      if ( layerDataIt->vectorLayer )
      {
        nFeatures += layerDataIt->vectorLayer->featureCount();
      }
    }
  }

  QProgressDialog* theProgressDialog = 0;
  if ( mShowProgressDialog )
  {
    theProgressDialog = new QProgressDialog( QObject::tr( "Building triangulation..." ), QObject::tr( "Abort" ), 0, nFeatures, 0 );
    theProgressDialog->setWindowModality( Qt::WindowModal );
  }


  QgsFeature f;
  QList<LayerData>::iterator layerDataIt = mLayerData.begin();
  for ( ; layerDataIt != mLayerData.end(); ++layerDataIt )
  {
    if ( layerDataIt->vectorLayer )
    {
      QgsAttributeList attList;
      if ( !layerDataIt->zCoordInterpolation )
      {
        attList.push_back( layerDataIt->interpolationAttribute );
      }

      QgsFeatureIterator fit = layerDataIt->vectorLayer->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( attList ) );

      while ( fit.nextFeature( f ) )
      {
        if ( mShowProgressDialog )
        {
          if ( theProgressDialog->wasCanceled() )
          {
            break;
          }
          theProgressDialog->setValue( nProcessedFeatures );
        }
        insertData( &f, layerDataIt->zCoordInterpolation, layerDataIt->interpolationAttribute, layerDataIt->mInputType );
        ++nProcessedFeatures;
      }
    }
  }

  delete theProgressDialog;

  if ( mInterpolation == CloughTocher )
  {
    CloughTocherInterpolator* ctInterpolator = new CloughTocherInterpolator();
    NormVecDecorator* dec = dynamic_cast<NormVecDecorator*>( mTriangulation );
    if ( dec )
    {
      QProgressDialog* progressDialog = 0;
      if ( mShowProgressDialog ) //show a progress dialog because it can take a long time...
      {
        progressDialog = new QProgressDialog();
        progressDialog->setLabelText( QObject::tr( "Estimating normal derivatives..." ) );
      }
      dec->estimateFirstDerivatives( progressDialog );
      delete progressDialog;
      ctInterpolator->setTriangulation( dec );
      dec->setTriangleInterpolator( ctInterpolator );
      mTriangleInterpolator = ctInterpolator;
    }
  }
  else //linear
  {
    mTriangleInterpolator = new LinTriangleInterpolator( theDualEdgeTriangulation );
  }
  mIsInitialized = true;

  //debug
  if ( mExportTriangulationToFile )
  {
    theDualEdgeTriangulation->saveAsShapefile( mTriangulationFilePath );
  }
}
Пример #28
0
void Mesh::computeCentricity(QWidget* guiParent)
{
	//	float maxCentricity = -FLT_MAX;
	//	float minCentricity = FLT_MAX;

	QProgressDialog *prog = NULL;
	if (guiParent)
		prog = new QProgressDialog("Building centricity", "Stop", 0, numVtx(), guiParent);
		
	int counter = 0;
	int total = size_of_vertices();
	for (Mesh::Vertex_iterator it = vertices_begin(); it != vertices_end(); ++it)
	{
		if (guiParent)
		{
			prog->setValue(counter);
			QCoreApplication::processEvents();
			if (prog->wasCanceled())
				return;
		}


		counter++;

		double distanceSum = 0.0;
		int count = 0;

		dijkstra(&*it);

		for (Mesh::Vertex_iterator n = vertices_begin(); n != vertices_end(); ++n)
		{
			if (n->distance() != FLT_MAX) 
			{
				count++;
				distanceSum += n->distance();
			}
		}
		it->centricity(distanceSum/(double)count);

		//	if (it->centricity() > maxCentricity) maxCentricity = it->centricity();
		//	if (it->centricity() < minCentricity) minCentricity = it->centricity();
		//	printf("%d = %f\n", counter, it->centricity());
	}

	delete prog;


	//if (m_normalize ) 
	//{
	//report("normalizing values");
	/*for (Mesh::Vertex_iterator it = m_mesh->vertices_begin();
	it != m_mesh->vertices_end(); 
	it++)
	{
	if (it->centricity() != FLT_MAX)
	it->centricity() = (it->centricity() - minCentricity) / (maxCentricity - minCentricity);
	}*/
	//normalizeByComponents();
	//}

	// facet centricity is the average of the vertices.

	float featureMin = FLT_MAX;
	float featureMax = -FLT_MAX;

	for (Mesh::Face_iterator fit = faces_begin(); fit != faces_end(); ++fit)
	{
		Face_handle fh = &*fit;
		float val = 0.0;
		for(int fii = 0; fii < fh->size(); ++fii)
		{
			Vertex_handle cv = fh->vertex(fii);
			val += cv->centricity();
		}
		val /= fh->size();

		fh->centricity() = val;

		if (val < featureMin) 
			featureMin = val;
		if (val > featureMax)
			featureMax = val;
	}

	float divwith = 1.0 / (featureMax - featureMin);
	for (Mesh::Face_iterator fit = faces_begin(); fit != faces_end(); ++fit)
	{
		Face_handle fh = &*fit;
		fh->centricity() = (fh->centricity() - featureMin) * divwith;
	}

	m_hasCentricity = true;
}
Пример #29
0
void SegmentFactory::makeSegments (const QImage &imageFiltered,
                                   const DocumentModelSegments &modelSegments,
                                   QList<Segment*> &segments)
{
  LOG4CPP_INFO_S ((*mainCat)) << "SegmentFactory::makeSegments";

  // Statistics that show up in debug spew
  int madeLines = 0;
  int shortLines = 0; // Lines rejected since their segments are too short
  int foldedLines = 0; // Lines rejected since they could be into other lines

  // debugging with modal progress dialog box is problematic so make switchable
  const bool useDlg = true;

  // For each new column of pixels, loop through the runs. a run is defined as
  // one or more colored pixels that are all touching, with one uncolored pixel or the
  // image boundary at each end of the set. for each set in the current column, count
  // the number of runs it touches in the adjacent (left and right) columns. here is
  // the pseudocode:
  //   if ((L > 1) || (R > 1))
  //     "this run is at a branch point so ignore the set"
  //   else
  //     if (L == 0)
  //       "this run is the start of a new segment"
  //     else
  //       "this run is appended to the segment on the left
  int width = imageFiltered.width();
  int height = imageFiltered.height();

  QProgressDialog* dlg;
  if (useDlg)
  {

    dlg = new QProgressDialog("Scanning segments in image", "Cancel", 0, width);
    ENGAUGE_CHECK_PTR (dlg);
    dlg->show();
  }

  bool* lastBool = new bool [height];
  ENGAUGE_CHECK_PTR(lastBool);
  bool* currBool = new bool [height];
  ENGAUGE_CHECK_PTR(currBool);
  bool* nextBool = new bool [height];
  ENGAUGE_CHECK_PTR(nextBool);
  SegmentVector lastSegment (height);
  SegmentVector currSegment (height);

  ColorFilter filter;
  loadBool(filter, lastBool, imageFiltered, -1);
  loadBool(filter, currBool, imageFiltered, 0);
  loadBool(filter, nextBool, imageFiltered, 1);
  loadSegment(lastSegment, height);

  for (int x = 0; x < width; x++) {

    if (useDlg) {

      // Update progress bar
      dlg->setValue(x);
      qApp->processEvents();

      if (dlg->wasCanceled()) {

        // Quit scanning. only existing segments will be available
        break;
      }
    }

    matchRunsToSegments(x,
                        height,
                        lastBool,
                        lastSegment,
                        currBool,
                        currSegment,
                        nextBool,
                        modelSegments,
                        &madeLines,
                        &foldedLines,
                        &shortLines,
                        segments);

    // Get ready for next column
    scrollBool(lastBool, currBool, height);
    scrollBool(currBool, nextBool, height);
    if (x + 1 < width) {
      loadBool(filter, nextBool, imageFiltered, x + 1);
    }
    scrollSegment(lastSegment, currSegment, height);
  }

  if (useDlg) {

    dlg->setValue(width);
    delete dlg;
  }

  removeEmptySegments (segments);

  LOG4CPP_INFO_S ((*mainCat)) << "SegmentFactory::makeSegments"
                                 << " linesCreated=" << madeLines
                                 << " linesTooShortSoRemoved=" << shortLines
                                 << " linesFoldedTogether=" << foldedLines;

  delete[] lastBool;
  delete[] currBool;
  delete[] nextBool;
}
Пример #30
0
bool AirportsData::import(QProgressDialog &progress, MainObject *mainObject){


    QHash<QString, QString> airports;
    QString msg;
    QTime tm;
    int ms;

    progress.setValue(0);
    progress.setWindowTitle("Scanning Airport Directories");
    progress.setRange(0, 50000);

    int c = 0;
    int found = 0;
    int air_added = 0;
    ms = tm.restart();
	
    // Removing cache file, if exists()
    if (QFile::exists(mainObject->data_file("airports.txt"))) {
            outLog("*** FGx airportsdata reload: cache file exists!");
            QFile::remove(mainObject->data_file("airports.txt"));
            outLog("*** FGx airportsdata reload: REMOVED AIRPORTS CACHE FILE");
    }

    //= Cache File
    QFile cacheFile( mainObject->data_file("airports.txt") );
    if(!cacheFile.open(QIODevice::WriteOnly | QIODevice::Text)){
            //qDebug() << "TODO Open error cachce file=";
            return true;
    }
    QTextStream out(&cacheFile);
    
    msg = "FGx airportsdata reload: Scanning apt.dat.gz in " + mainObject->X->fgroot() + "/Airports/apt.dat.gz";
    outLog(msg);
    airports = getAirportNameMap(mainObject);

    //================================================
    //* Lets Loop the directories
    //* Get out aiports path from setings and get the the subdir also
    QDirIterator loopAirportsFiles( mainObject->X->airports_path(), QDirIterator::Subdirectories );
    QString xFileName;

    msg = "FGx airportsdata reload: Scanning XML files in "+mainObject->X->airports_path();
    outLog(msg);
    progress.setWindowTitle(msg);
    progress.setRange(0, 50000);

    // Check the fgfs additional argument list,
    // and/or any additional scenery path inputs
    // *** take care NOT to duplicate ***
    QStringList fgfs_args = mainObject->X->get_fgfs_args();
    int i, ind;
    QDir d;
    QString path;
#ifdef Q_OS_WIN
    QChar psep(';');
#else
    QChar psep(':');
#endif
	
    // AIIIIII, found the doubler !, said yves very very loud - well done said pete ;-)
    for (i = 0; i < fgfs_args.size(); i++) {
        msg = fgfs_args.at(i);
        ind = msg.indexOf(QChar('"'));
        if (ind == 0)
            msg = msg.mid(1,msg.length()-2);
        if (msg.indexOf("--fg-scenery=") == 0) {
            // got a scenery folder to scan
            msg = msg.mid(13);
            ind = msg.indexOf(QChar('"'));
            if (ind == 0)
                msg = msg.mid(1,msg.length()-2);
            QStringList path_list = msg.split(psep);
            int pathnumber = 0;
            for( QStringList::ConstIterator entry = path_list.begin(); entry != path_list.end(); entry++) {
                path = *entry;
				pathnumber = pathnumber + 1;
                if (d.exists(path)) {
                    // we have a PATH to check, but we are ONLY checking 'Airports'
                    if ( !(path.indexOf(QChar('/')) == (path.size()-1)) &&
                         !(path.indexOf(QChar('\\')) == (path.size()-1)) )
                        path.append("/");
                    path.append("Airports"); // XML is only in here
                    if (!d.exists(path))
                        continue;
                    QDirIterator loopFiles( path, QDirIterator::Subdirectories );
                    while (loopFiles.hasNext()) {

                        //= Get file handle if there is one
                        xFileName = loopFiles.next();

                        //= Check if file entry is a *.threshold.xml - cos this is what we want
                        if(xFileName.endsWith(".threshold.xml") ){

                            //= Split out "CODE.threshold.xml" with a "."
                            QFileInfo fileInfoThreshold(xFileName);
                            QString airport_code = fileInfoThreshold.fileName().split(".").at(0);

                            //* Update progress
                            if(c % 100 == 0){
                                progress.setValue(c);
                                progress.setLabelText(xFileName);
                                progress.repaint();
                            }

                            QString airport_name("");
                            if(airports.contains(airport_code)){
                                airport_name = airports.value(airport_code);
                            }

                            QStringList cols; // missing in middle is description ??
                            cols << airport_code << airport_name << fileInfoThreshold.absoluteDir().absolutePath() << QString::number(pathnumber);

                            out << cols.join("\t").append("\n");
                            air_added++;

                            found++;
                        }

                        if(progress.wasCanceled()){
                            progress.hide();
                            return true;
                        }
                        c++;
                    }
                }
            }
        }
    }


    cacheFile.close();

    msg.sprintf("*** FGx airportsdata reload: Walked %d files, found %d threshold.xml, appended %d to cache",
                c, found, air_added);
    outLog(msg+", in "+getElapTimeStg(tm.elapsed()));
    progress.hide();
    return false;
}