Ejemplo n.º 1
0
void QueryFinishWizardPage::initializePage()
{
	m_result->clear();
	ui.progressBar->setValue(0);
	Framework* fw = framework();
	setCurrentAction(tr("Collecting information..."));
	quint32 storeId = field("store").value<quint32>();
	const QString queryStr = field("query").toString();
	setCurrentAction(tr("Looking for store..."));
	const DataStore* dataStore = fw->dataStoreById(storeId);
	if(dataStore == NULL) return;
	setCurrentAction(tr("Store found..."));
	setCurrentAction(tr("Parsing query..."));
	CGSQL_NS::RootNode *root = CGSQL_NS::QueryParser::parse(queryStr.toStdString());
	if (root == NULL)
	{
		setCurrentAction("Error while parting query.");
		return;
	}
	pgn::GameCollection loadedGames;
	setCurrentAction(tr("Retrieving games from %1...").arg(dataStore->name().toLower()));
	bool loadResult = dataStore->load(root, loadedGames);
	if(!loadResult)
	{
		setCurrentAction(tr("Can not load games from %1...").arg(dataStore->name().toLower()));
		return;
	}
	setCurrentAction(tr("Loaded %1 games. Looking for concepts in its...").arg(loadedGames.size()));
	QProgressDialog* progressDialog = new QProgressDialog("Searching for concepts", "Cancel", 0, loadedGames.size());
	progressDialog->setWindowModality(Qt::WindowModal);
	progressDialog->setValue(0);
	int progress = 0;
	for(pgn::GameCollection::iterator it = loadedGames.begin();
		it != loadedGames.end();
		++it)
	{
		progressDialog->show();
		m_result->data().addGame(&(*it));
		if(root->body()->accept(&(m_result->data())))
			m_result->games().insert(*it);
		progressDialog->setValue(progress);
		++progress;
	}
	progressDialog->setValue(100);
	progressDialog->setAutoClose(true);
	progressDialog->reset();
	progressDialog->show();
	progressDialog->deleteLater();
	ui.progressBar->setValue(100);
}
Ejemplo n.º 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());
}
Ejemplo n.º 3
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;
}
Ejemplo n.º 4
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);
    }
  }
Ejemplo n.º 5
0
void CandidateIndexesPage::generateCandidates()
{
    if (generator != nullptr) {
        return;
    }

    MainWizard *mainWizard = static_cast<MainWizard*>(wizard());

    QProgressDialog *progress = new QProgressDialog(
        tr("Generating candidates..."),
        tr("Cancel"),
        0,
        100,
        this
    );

    progress->setModal(true);
    progress->setValue(0);
    progress->setMinimumDuration(0);

    generator = new GenerateCandidateIndexes(mainWizard->project);
    connect(generator, SIGNAL(finished()), progress, SLOT(accept()));
    connect(generator, SIGNAL(progress(int)), progress, SLOT(setValue(int)));
    connect(generator, SIGNAL(resultReady()), this, SLOT(candidatesGenerated()));
    connect(progress, SIGNAL(canceled()), generator, SLOT(terminate()));
    generator->start();
}
Ejemplo n.º 6
0
void MainWindow::on_actionVista_Previa_triggered()
{
    QProgressDialog* pDlg = new QProgressDialog(this);
    pDlg->setMaximum(0);
    pDlg->setValue(0);
    pDlg->show();

    QPrinter * printer = new QPrinter();
    QPrintDialog dlg(printer,this);
  //  bool error;

    QDomDocument doc = paper.preview();
    render = new ReportRenderer();

    render->setPrinter(printer);
    render->setDocIn(doc);
    QMap<QString,QString> c;
    c["Empresa.cab_fac"] = "id = 1";
    c["Empresa.lin_fac"] = "id_cab = 1";
    render->setQueryClausules(c);

    QtConcurrent::run(render, &ReportRenderer::PreRender);
    connect(render,SIGNAL(end()),pDlg,SLOT(deleteLater()));
    connect(render,SIGNAL(end()),this,SLOT(previewReady()));
}
Ejemplo n.º 7
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();
}
Ejemplo n.º 8
0
void Operation::perform()
{
    pd->setValue(steps);
    //... perform one percent of the operation
    steps++;
    if (steps > pd->maximum())
        t->stop();
}
Ejemplo n.º 9
0
int DicomImageSet::parseFolder(QString folderName)
{
	QStringList fileList = getAllFiles(folderName);
    HRESULT hr = CoInitialize(NULL);
    if (!SUCCEEDED(hr))
    {
		return NULL;
    }

    hr = S_OK;
    IXMLDOMDocument *pXMLDom = NULL;
    IXMLDOMElement *pRoot = NULL;

    BSTR bstrXML = NULL;
    VARIANT varFileName;
    VariantInit(&varFileName);

	QProgressDialog progress (QString("Parsing all files in %1").arg(folderName), QString("Cancel"), 0, fileList.count());

    CHK_HR(CreateAndInitDOM(&pXMLDom));

    // Create a processing instruction element.
    CHK_HR(CreateAndAddPINode(pXMLDom, L"xml", L"version='1.0'"));
    
    // Create the root element.
    CHK_HR(CreateElement(pXMLDom, L"root", &pRoot));

    // Create an attribute for the <root> element, with name "created" and value "using dom".
	CHK_HR(CreateAndAddAttributeNode(pXMLDom, L"path", folderName.toStdWString().c_str(), pRoot));

    // Add NEWLINE for identation before </root>.
    CHK_HR(CreateAndAddTextNode(pXMLDom, L"\n", pRoot));
    // add <root> to document
    CHK_HR(AppendChildToParent(pRoot, pXMLDom));

	progress.show();
	for (int i=0; i<fileList.count(); ++i)
	{
		insertFileItem(pXMLDom, pRoot, folderName, fileList[i]);
		progress.setValue(i);
	}

	CHK_HR(VariantFromString(QDir(folderName).filePath(DATASET_FILE_NAME).toStdWString().c_str(), varFileName));
    CHK_HR(pXMLDom->save(varFileName));

CleanUp:
    SAFE_RELEASE(pRoot);
    SysFreeString(bstrXML);
    VariantClear(&varFileName);

    CoUninitialize();
	if (FAILED(hr))
	{
		SAFE_RELEASE(pXMLDom);
		return 0;
	}
	return 1;
}
Ejemplo n.º 10
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;
}
Ejemplo n.º 11
0
void ProgressDialog::updateProgress(float progress, const QString &stepString) {
  progressDialog->setValue(int(progress * 100));
  QString message(stepString);
  if (message.length() > 33)
    message = message.left(17) + "..." + message.right(12);
  progressDialog->setLabelText(message);
  progressDialog->update();
  qApp->processEvents();
}
Ejemplo n.º 12
0
void MainWindow::LoadFile()
{

    if (FileFormatPluginList.size()) {


        QString FileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                     "",
                                                     FileFormatPluginList[0]->getFormatDescription());

        //test();
        // Create a progress dialog.
            QProgressDialog dialog;

            dialog.setLabelText(QString("Загрузка данных из файла"));

            // Create a QFutureWatcher and connect signals and slots.
            QFutureWatcher<void> futureWatcher;
            QTimer timer;
            connect(&timer, SIGNAL(timeout()), this, SLOT(updateProgress()));
            timer.start(1000);
            QObject::connect(&futureWatcher, SIGNAL(finished()), &dialog, SLOT(reset()));
            QObject::connect(&dialog, SIGNAL(canceled()), SLOT(cancelOperation()));
            QObject::connect(&dialog, SIGNAL(canceled()), &futureWatcher, SLOT(cancel()));
            QObject::connect(this, SIGNAL(progressValueChanged(int)), &dialog, SLOT(setValue(int)));

            //extern void FileFormatPluginList[0]->getDataFromChannel(channel,(qint8*)data);


            QFuture<void> future = QtConcurrent::run(FileFormatPluginList[0], &FileReadInterface::LoadFile, FileName);

            // Start the computation.
            futureWatcher.setFuture(future);

            // Display the dialog and start the event loop.
            dialog.exec();

            futureWatcher.waitForFinished();
            dialog.setValue(100);
            dialog.hide();


            timer.stop();



        cube= FileFormatPluginList[0]->getCube();


        QList<double> list = cube->GetListOfChannels();




        foreach(double l , list) {
            ui->ChannelListWidget->addItem(QString("%1").arg(l));
        }
Ejemplo n.º 13
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;
      }
void MountainViewWidgetPrivate::update_clips_view(SSTimeSeriesWidget *W,SSTimeSeriesView *V,int label)
{
    QProgressDialog dlg;
	dlg.setWindowTitle(QString("Extracting clips for template %1").arg(label));
    dlg.setRange(0,100);
    dlg.show();
	dlg.setLabelText(QString("Extracting clips for template %1...").arg(label));
    dlg.setValue(0); dlg.repaint(); qApp->processEvents();
    Mda clips=extract_clips(m_raw,m_times,m_labels,label);
    dlg.setLabelText("Formatting clips...");
    dlg.setValue(50); dlg.repaint(); qApp->processEvents();
    Mda clips2=format_clips(clips,m_template_view_padding);
    DiskArrayModel *MM=new DiskArrayModel;
    MM->setFromMda(clips2);
    dlg.setLabelText("Initializing...");
    dlg.setValue(75); dlg.repaint(); qApp->processEvents();
    V->setData(MM,true);
    V->initialize();
    W->setClipData(clips);
    W->setWindowTitle(QString("Spike Clips -- template %1 -- %2 spikes").arg(label).arg(clips.N3()));
}
Ejemplo n.º 15
0
/*=========================================================================
  doFileSearch 
=========================================================================*/
void MainWindow::doFileSearch (const QString &path, const QString &text, 
    KFileList *fileList)
  {
  QProgressDialog progress (tr("Searching..."), tr("Stop"), 
      0, 100, this);
  progress.setWindowModality (Qt::WindowModal);
  progress.setMinimumDuration (0);
  progress.show();

  _doFileSearch (path, "", text, fileList, progress);

  progress.setValue (100);
  }
Ejemplo n.º 16
0
void SearchDialog::newSearch() {
  QString phrase = QInputDialog::getText(pgView, "Search in notebook",
                                         "Search phrase:",
                                         QLineEdit::Normal,
                                         lastPhrase);
  lastPhrase = phrase;

  if (phrase.isEmpty())
    return;

  QProgressDialog *progress = new QProgressDialog(pgView);
  progress->setLabelText("Searching...");
  progress->setCancelButton(0);
  progress->setMinimumDuration(500);
  progress->setValue(0);
  Search *search = new Search(pgView->notebook());
  QList<SearchResult> res = search->immediatelyFindPhrase(phrase);

  if (res.isEmpty()) {
    delete progress;
    QMessageBox::information(pgView, "Search - eln",
                             QString::fromUtf8("Search phrase “%1” not found")
                             .arg(phrase));
    return;
  }
  
  SearchResultScene *scene
    = new SearchResultScene(phrase,
			    QString::fromUtf8("Search results for “%1”")
			    .arg(phrase),
			    res,
			    pgView->notebook()->bookData());
  scene->populate();
  connect(scene,
	  SIGNAL(pageNumberClicked(int, Qt::KeyboardModifiers,
				   QString, QString)),
	  this,
	  SLOT(gotoPage(int, Qt::KeyboardModifiers, QString, QString)));
  SearchView *view = new SearchView(scene);
  view->setAttribute(Qt::WA_DeleteOnClose, true);
  connect(parent(), SIGNAL(destroyed()), view, SLOT(close()));
  delete progress;
  
  view->resize(pgView->size()*.9);
  QString ttl = pgView->notebook()->bookData()->title();
  view->setWindowTitle("Search in: "
		       + ttl.replace(QRegExp("\\s\\s*"), " ") + " - eln");
  view->show();
}
Ejemplo n.º 17
0
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();
}
Ejemplo n.º 18
0
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;
}
Ejemplo n.º 19
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;
}
Ejemplo n.º 20
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;
    }
Ejemplo n.º 21
0
bool MainWindow::parseDirectory(QString dirName, parseType type,bool convert,bool create,QProgressDialog &progress)
{
    QFileInfoList list;
    QStringList filter;
    QDir dir(dirName);

    /* create filter list for files */
    filter.append(QString("*.h"));
    filter.append(QString("*.c"));
    filter.append(QString("*.cpp"));
    filter.append(QString("*.cxx"));

    /* parse files in current directory */
    list = dir.entryInfoList(filter,QDir::Files);
    progress.setMaximum(progress.maximum()+list.size());
    for(int i = 0;i<list.size();i++)
    {
        /* increase progress bar */
        progress.setValue(progress.value()+1);

        if(convert)
        {
            if(!parser.converteFile(list.at(i).absoluteFilePath()))
                return false;
        }
        else
        {
            if(!parser.parseFile(list.at(i).absoluteFilePath()))
                return false;
        }

        progress.setLabelText(list.at(i).absoluteFilePath());
    }

    /* go recursive through all the subdiectories */
    list = dir.entryInfoList(QDir::Dirs|QDir::NoDotAndDotDot);
    for(int i = 0;i<list.size();i++)
    {
        if(!parseDirectory(list.at(i).absoluteFilePath(),type,convert,create,progress))
            return false;
    }

    return true;
}
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();
}
Ejemplo n.º 23
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;
}
Ejemplo n.º 24
0
void Polar::setPolarName(QString fname)
{
    isCsv=true;
    loaded=false;
    clearPolar();
    if(this->mainWindow->getSelectedBoat() && this->mainWindow->getSelectedBoat()->get_boatType()==BOAT_REAL)
        coeffPolar=Settings::getSetting("polarEfficiency",100).toInt()/100.0;
    else
        coeffPolar=1.0;

    //qWarning() << "Opening polar" << fname<<"with coeff"<<coeffPolar;

    name=fname;
    QString nameF = appFolder.value("polar")+fname+".csv";
    QFile file(nameF);
    if (fname.endsWith(".csv",Qt::CaseInsensitive) || fname.endsWith(".pol",Qt::CaseInsensitive))
    {
        nameF=appFolder.value("polar")+fname;
        file.setFileName(nameF);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text ))
        {
            QMessageBox::warning(0,QObject::tr("Lecture de polaire"),
                QString(QObject::tr("Impossible d'ouvrir le fichier %1")).arg(name));
            return;
        }

        isCsv=fname.endsWith("csv",Qt::CaseInsensitive);
    }
    else
    {
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text ))
        {
            isCsv=false;
            nameF = appFolder.value("polar")+fname+".pol";
            file.setFileName(nameF);
            if (!file.open(QIODevice::ReadOnly | QIODevice::Text ))
            {
                 QMessageBox::warning(0,QObject::tr("Lecture de polaire"),
                     QString(QObject::tr("Impossible d'ouvrir le fichier %1 (ni en .csv ni en .pol)")).arg(name));
                 return;
            }
        }
    }
    QTextStream stream(&file);
    QString line;
    QStringList list;
    /* read first line to see line length */
    line=stream.readLine();
    line.remove("\"");
    if(line.isNull())
    {
        QMessageBox::warning(0,QObject::tr("Lecture de polaire"),
             QString(QObject::tr("Fichier %1 vide")).arg(fname));
        file.close();
        return;
    }
    if(isCsv)
        list = line.split(';');
    else
        list = line.split('\t');
    if(list[0].toUpper() != "TWA\\TWS" && list[0].toUpper() != "TWA/TWS" && list[0].toUpper() != "TWA")
    {
        QMessageBox::warning(0,QObject::tr("Lecture de polaire"),
             QString(QObject::tr("Fichier %1 invalide (doit commencer par TWA\\TWS et non '%2')"))
                        .arg(fname)
                        .arg(list[0]));
        file.close();
        return;
    }
    int i;
    for(i=1;i<list.count();++i)
    {
        if(!tws.isEmpty() && list[i].toDouble()<=tws.last()) break;
        tws.append(list[i].toDouble());
    }
    bool missingTws0=false;
    if(tws.first()!=0.0)
    {
        missingTws0=true;
    }
    bool firstTWA=true;
    while(true)
    {
        line=stream.readLine();
        if(line.isNull()) break;
        line.remove("\"");
        if (isCsv)
            list = line.split(";");
        else
            list = line.split("\t");
        if(firstTWA)
        {
            firstTWA=false;
            if(list.first().toDouble()!=0.0)
            {
                for(int t=0;t<tws.count();++t)
                {
                    polar_data.append(0);
                }
                if(missingTws0)
                    polar_data.append(0);
                twa.append(0.0);
            }
        }
        twa.append(list[0].toDouble());
        if(missingTws0)
            polar_data.append(0);
        for(i=1;i<list.count();++i)
        {
            if(i>tws.count()) break;
            polar_data.append(list[i].toDouble()*this->coeffPolar);
        }
        while(i<=tws.count())
            polar_data.append(0);
    }
    if(missingTws0)
        tws.prepend(0.0);
#if 0
    qWarning()<<"polar data for"<<nameF;
    QString debug="xxx.x ";
    foreach(double dd,tws)
        debug+=QString().sprintf("%04.1f ",dd);
    qWarning()<<debug;
    QListIterator<double> i1(polar_data);
    QListIterator<double> i2(twa);
    while(i2.hasNext())
    {
        debug=QString().sprintf("%05.1f ",i2.next());
        for(int nn=0;nn<tws.count();++nn)
            debug+=QString().sprintf("%04.1f ",i1.next());
        qWarning()<<debug;
    }
#endif

    mid_twa=qRound(twa.count()/2.0);
    mid_tws=qRound(tws.count()/2.0);
    /* polaire chargee */

/* pre-calculate B-VMG for every tws at 0.1 precision with a twa step of 1 and then .1 */

    double ws=0.0;
    double wa=0.0;
    double bvmg,bvmg_d,bvmg_u,wa_u,wa_d,wa_limit;
    maxSpeed=0.0;
    do
    {
        wa_u=0.0;
        wa_d=180.0;
        bvmg_u=bvmg_d=0;
        double speed;
        do
        {
            speed=myGetSpeed(ws,wa,true);
            if(speed>maxSpeed) maxSpeed=speed;
            bvmg=speed*cos(degToRad(wa));
            if(bvmg_u<bvmg) //bvmg is positive here
            {
                bvmg_u=bvmg;
                wa_u=wa;
            }
            if(bvmg_d>bvmg) //bvmg is negative here
            {
                bvmg_d=bvmg;
                wa_d=wa;
            }
            wa=qRound(wa+1);
        } while(wa<181.00);
        wa=wa_u-1;
        wa_limit=wa_u+1;
        if(wa<0) wa=0.0;
        if(wa_limit<1) wa_limit=1.0;
        if(wa_limit>180) wa_limit=180.0;
        bvmg_u=0.0;
        do
        {
            speed=myGetSpeed(ws,wa,true);
            if(speed>maxSpeed) maxSpeed=speed;
            bvmg=speed*cos(degToRad(wa));
            if(bvmg_u<bvmg)
            {
                bvmg_u=bvmg;
                wa_u=wa;
            }
            wa=wa+0.1;
        } while(wa<(wa_limit+0.1000));
        wa=wa_d-1;
        wa_limit=wa_d+1;
        if(wa<0) wa=0.0;
        if(wa_limit<1) wa_limit=1.0;
        if(wa_limit>180) wa_limit=180.0;
        bvmg_d=0.0;
        do
        {
            speed=myGetSpeed(ws,wa,true);
            if(speed>maxSpeed) maxSpeed=speed;
            bvmg=speed*cos(degToRad(wa));
            if(bvmg_d>bvmg)
            {
                bvmg_d=bvmg;
                wa_d=wa;
            }
            wa=wa+0.1;
        }while(wa<wa_limit+0.1);
        best_vmg_up.append(wa_u);
        best_vmg_down.append(wa_d);
        wa=0.0;
        ws=ws+.1;
    }while(ws<60.1);
    loaded=true;
    QFileInfo fi(file.fileName());
    QString nameFVmg = appFolder.value("polar")+fi.baseName()+".vmg";
    fileVMG.setFileName(nameFVmg);
    if (fileVMG.open(QIODevice::ReadOnly | QIODevice::Text ))
    {
        if(fileVMG.size()<4329500 || fileVMG.size()>4329700)
            fileVMG.remove();
        else
        {
            QFileInfo info1(fileVMG);
            QFileInfo info2(file);
            if(this->mainWindow->isStartingUp && info1.lastModified()<info2.lastModified())
                fileVMG.remove();
            else
            {
                file.close();
                return;
            }
        }
    }
    file.close();
//precalculate regular VMGs
    //qWarning() << "Start computing vmg";
    fileVMG.open(QIODevice::WriteOnly | QIODevice::Text );
    double vmg=0;
    QTextStream sVmg(&fileVMG);
    QString ssVmg;
    QProgressDialog * progress;
    progress=new QProgressDialog((QWidget*)mainWindow);
    progress->setWindowModality(Qt::ApplicationModal);
    progress->setLabelText(tr("Pre-calcul des valeurs de VMG pour ")+fname);
    progress->setMaximum(600);
    progress->setMinimum(0);
    progress->setCancelButton(NULL);
    progress->setMaximumHeight(100);
    progress->show();
    for (int tws=0;tws<601;tws++)
    {
        progress->setValue(tws);
        for (int twa=0;twa<1801;twa++)
        {
            bvmgWind((double) twa/10.0,(double) tws/10.0,&vmg);
            ssVmg.sprintf("%.4d",qRound(A360(vmg)*10.0));
            sVmg<<ssVmg;
        }
    }
    fileVMG.close();
    if(!fileVMG.open(QIODevice::ReadOnly | QIODevice::Text ))
        qWarning()<<"fileVMG could not be re-opened!";
    progress->close();
    delete progress;
}
Ejemplo n.º 25
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;
}
void Hypergraph::updateLayout(const vector<int> &changedSet, int boundary [], int dim, float c)
{
	_layoutDim = dim;
	int nIteration = 500;
	float temperature = 10;

	srand(time(NULL));

	int area = 1;
	for (int i=0; i<dim; ++i)
	{
		area *= boundary[2*i+1]-boundary[2*i];
	}
	float k = c*sqrt(area*1.0f/_nVertices);

	int nEdges = _edges.size();
	int nTotal = _nVertices+nEdges;
	vector<fvec> dispBuf (nTotal);
	for (int i=0; i<nTotal; ++i)
	{
		dispBuf[i] = fvec(dim);
	}
	int i,j;

	vector<bool> bMovable (nTotal);
	for (i=0; i<changedSet.size(); ++i)
	{
		bMovable[changedSet[i]] = true;
	}

	QProgressDialog prog ("Performing graph layout ...", "", 0, nIteration-1);
	prog.setCancelButton(NULL);
	for (int it=0; it<nIteration; ++it)
	{
		DWORD t1 = GetTickCount();
		bool bChanged = false;
		for (i=0; i<nTotal; ++i)
		{
			dispBuf[i].fill(0);
		}

		DWORD t2 = GetTickCount();
		/*calculate repulsive force*/
		for (i=0; i<changedSet.size(); ++i)
		{
			int idx = changedSet[i];
			for (j=0; j<nTotal; ++j)
			{
				if (j==idx)
				{
					continue;
				}
				fvec d = _layout[j]-_layout[idx];
				fvec disp;
				float normD = norm(d,2);
				if (normD<1.0e-5)
				{
					disp = fvec(dim);
					for (int iDim=0; iDim<dim; ++iDim)
					{
						disp(iDim) = rand()%100/100.0f;
					}
					disp *= temperature;
				} else
				{
					disp = d*k*k/pow(normD,2);
				}
				dispBuf[idx] -= disp;
			}
		}

		DWORD tRepForce = GetTickCount()-t2;

		/*calculate attractive force*/
		for (i=0; i<_edges.size(); ++i)
		{
			int edgeIdx = i+_nVertices;
			for (j=0; j<_edges[i].size(); ++j)
			{
				if (!bMovable[_edges[i][j]])
				{
					continue;
				}
				float c2 = 3.0;
				fvec d1 = _layout[edgeIdx] - _layout[_edges[i][j]];
				fvec disp1 = c2*d1*norm(d1,2)/k;
				dispBuf[edgeIdx] -= disp1;
				dispBuf[_edges[i][j]] += disp1;

				for (int m=0; m<_edges[i].size(); ++m)
				{
					if (m==j)
					{
						continue;
					}
					fvec d = _layout[_edges[i][m]] - _layout[_edges[i][j]];
					fvec disp = d*norm(d,2)/k;
					dispBuf[_edges[i][j]] += disp;
				}
			}
		}
		DWORD tRepAttrForces = GetTickCount()-t2;

		/*restrict the points from being pushed towards the boundary*/
		for (i=0; i<nTotal; ++i)
		{
			if (!bMovable[i])
			{
				continue;
			}
			for (j=0; j<dim; ++j)
			{
				float c1=1.0e6;
				float x = _layout[i](j);
				if (x==boundary[j*2] || x==boundary[j*2+1])
				{
					int stop = 1;
				}
				float d = c1*(1/(x-boundary[j*2]+1.0e-3)-1/(boundary[j*2+1]-x+1.0e-3));
				dispBuf[i](j) += d;
			}
		}

		/*limit the maximum displacement, boundary check*/
		for (i=0; i<nTotal; ++i)
		{
			if (!bMovable[i])
			{
				continue;
			}
			float n = norm(dispBuf[i],2);
			fvec newLayout = _layout[i]+dispBuf[i]*min(n, temperature)/n;
			for (j=0; j<dim; ++j)
			{
				int minBoundary = boundary[2*j];
				int maxBoundary = boundary[2*j+1];
				newLayout(j) = newLayout(j) < minBoundary?minBoundary:(newLayout(j)>maxBoundary?maxBoundary:newLayout(j));
			}
			if (norm(newLayout-_layout[i], 2)>1.0e-3)
			{
				_layout[i] = newLayout;
				bChanged = true;
			}
		}

		if (!bChanged)
		{
			break;
		}

		DWORD perItTime = GetTickCount() - t1;
		t1 = GetTickCount();

		prog.setValue(it);
	}
}
Ejemplo n.º 27
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);
}
Ejemplo n.º 28
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;
}
Ejemplo n.º 29
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();
    }
}
Ejemplo n.º 30
0
void MainWindow::launchInstance(InstancePtr instance, AuthSessionPtr session, BaseProfilerFactory *profiler)
{
	Q_ASSERT_X(instance != NULL, "launchInstance", "instance is NULL");
	Q_ASSERT_X(session.get() != nullptr, "launchInstance", "session is NULL");

	QString launchScript;

	if(!instance->prepareForLaunch(session, launchScript))
		return;

	MinecraftProcess *proc = new MinecraftProcess(instance);
	proc->setLaunchScript(launchScript);
	proc->setWorkdir(instance->minecraftRoot());

	this->hide();

	console = new ConsoleWindow(proc);
	connect(console, SIGNAL(isClosing()), this, SLOT(instanceEnded()));

	proc->setLogin(session);
	proc->arm();

	if (profiler)
	{
		QString error;
		if (!profiler->check(&error))
		{
			QMessageBox::critical(this, tr("Error"), tr("Couldn't start profiler: %1").arg(error));
			proc->abort();
			return;
		}
		BaseProfiler *profilerInstance = profiler->createProfiler(instance, this);
		QProgressDialog dialog;
		dialog.setMinimum(0);
		dialog.setMaximum(0);
		dialog.setValue(0);
		dialog.setLabelText(tr("Waiting for profiler..."));
		connect(&dialog, &QProgressDialog::canceled, profilerInstance, &BaseProfiler::abortProfiling);
		dialog.show();
		connect(profilerInstance, &BaseProfiler::readyToLaunch, [&dialog, this, proc](const QString &message)
		{
			dialog.accept();
			QMessageBox msg;
			msg.setText(tr("The launch of Minecraft itself is delayed until you press the "
						   "button. This is the right time to setup the profiler, as the "
						   "profiler server is running now.\n\n%1").arg(message));
			msg.setWindowTitle(tr("Waiting"));
			msg.setIcon(QMessageBox::Information);
			msg.addButton(tr("Launch"), QMessageBox::AcceptRole);
			msg.exec();
			proc->launch();
		});
		connect(profilerInstance, &BaseProfiler::abortLaunch, [&dialog, this, proc](const QString &message)
		{
			dialog.accept();
			QMessageBox msg;
			msg.setText(tr("Couldn't start the profiler: %1").arg(message));
			msg.setWindowTitle(tr("Error"));
			msg.setIcon(QMessageBox::Critical);
			msg.addButton(QMessageBox::Ok);
			msg.exec();
			proc->abort();
		});
		profilerInstance->beginProfiling(proc);
		dialog.exec();
	}
	else
	{
		proc->launch();
	}
}