Ejemplo n.º 1
0
void FilesystemWidget::CheckIntegrity(const DiscIO::Partition& partition)
{
  QProgressDialog* dialog = new QProgressDialog(this);
  std::future<bool> is_valid = std::async(
      std::launch::async, [this, partition] { return m_volume->CheckIntegrity(partition); });

  dialog->setLabelText(tr("Verifying integrity of partition..."));
  dialog->setWindowFlags(dialog->windowFlags() & ~Qt::WindowContextHelpButtonHint);
  dialog->setWindowTitle(tr("Verifying partition"));

  dialog->setMinimum(0);
  dialog->setMaximum(0);
  dialog->show();

  while (is_valid.wait_for(std::chrono::milliseconds(50)) != std::future_status::ready)
    QCoreApplication::processEvents();

  dialog->close();

  if (is_valid.get())
    QMessageBox::information(nullptr, tr("Success"),
                             tr("Integrity check completed. No errors have been found."));
  else
    QMessageBox::critical(nullptr, tr("Error"),
                          tr("Integrity check for partition failed. The disc image is most "
                             "likely corrupted or has been patched incorrectly."));
}
Ejemplo n.º 2
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.º 3
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.º 4
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;
      }
Ejemplo n.º 5
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();
}
Ejemplo n.º 6
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();
}
void ShortestPathComputer::init(ccMesh *mesh, QWidget *parentWidget/* = NULL*/)
{
    mMesh = mesh;
    ccGenericPointCloud *cloud = mesh->getAssociatedCloud();
    const unsigned vertexNum = cloud->size();
    const unsigned triangleNum = mesh->size();
    const unsigned edgeNum = triangleNum * 3; //半边

    Edge *edges = new Edge[edgeNum];
    float *edgeWeights = new float[edgeNum];
    const unsigned triangleEdgeVertexIndexs[3][2] = 
    {
        0, 1,
        1, 2,
        2, 0
    };
    unsigned edgeIndexBase, edgeIndex;
    mesh->placeIteratorAtBegining();
    for (unsigned i = 0; i < triangleNum; i++)
    {
        CCLib::TriangleSummitsIndexes* indexs = mesh->getNextTriangleIndexes();

        assert(indexs->i[0] < vertexNum && indexs->i[1] < vertexNum && indexs->i[2] < vertexNum);

        const CCVector3 *triangleVertices[3] = 
        {
            cloud->getPoint(indexs->i[0]),
            cloud->getPoint(indexs->i[1]),
            cloud->getPoint(indexs->i[2])
        };

        edgeIndexBase = i * 3;
        for (unsigned j = 0; j < 3; j++)
        {
            edgeIndex = edgeIndexBase + j;
            edges[edgeIndex].first = indexs->i[triangleEdgeVertexIndexs[j][0]];
            edges[edgeIndex].second = indexs->i[triangleEdgeVertexIndexs[j][1]];
            edgeWeights[edgeIndex] = CCVector3::vdistance(triangleVertices[triangleEdgeVertexIndexs[j][0]]->u, triangleVertices[triangleEdgeVertexIndexs[j][1]]->u);
        }
    }

    //开启新线程初始化BGL图并显示进度条
    BoostGraphInitThread thread;
    thread.setGraphData(&mGraph, edges, edgeNum, edgeWeights, vertexNum);
    thread.start();

    QProgressDialog progress;
    if (parentWidget)
    {
        progress.setParent(parentWidget);
    }
    progress.setWindowModality(Qt::WindowModal);
    progress.setWindowFlags(Qt::SubWindow | Qt::Popup);
    progress.setMinimumWidth(200);
    progress.setCancelButton(0);
    progress.setWindowTitle(QString::fromAscii("BGL图初始化"));
    progress.setLabelText(QString::fromAscii("BGL图初始化中,请稍后..."));
    progress.setRange(0, 0);
    progress.show();

    while (thread.isRunning())
    {
        QApplication::processEvents();
    }

    progress.close();

    //mGraph = MyGraph(edges, edges + edgeNum, edgeWeights, vertexNum);
}
Ejemplo n.º 8
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.º 9
0
void ProgressDialog::hideProgressDialog() {
  progressDialog->close();
  delete progressDialog;
  progressDialog = NULL;
}
Ejemplo n.º 10
0
void AQWebApplication::handleWebEvent(const QString &msgEvent)
{
  QStringList args(QStringList::split(AQ_MSG_SEP, msgEvent, true));
  AQ::EventType evT = webEventTypeToAQEventType(args[0]);
  QWidget *w;
  AQWidgetInfo *wInfo;

  if (evT != AQ::XProgressDialog) {
    w = AQ_WIDGET(args[1].toULongLong(0, 36));
    wInfo = createdWidgets_.find(w);
    if (!wInfo)
      return;
  }

  switch (evT) {
    case AQ::MouseButtonPress: {
      QWidget *popup = activePopupWidget();
      if (popup && popup != w->topLevelWidget())
        popup->close();

      w->raise();
      w->setActiveWindow();

      QPoint local(args[2].toInt(), args[3].toInt());
      QPoint global(w->mapToGlobal(local));
      QCursor::setPos(global);
      QMouseEvent mev(QEvent::MouseButtonPress, local, global, toQtButton(args[4]), toQtButtonState(args[5]));
      qt_sendSpontaneousEvent(w, &mev);
      break;
    }

    case AQ::MouseButtonRelease: {
      QPoint local(args[2].toInt(), args[3].toInt());
      QPoint global(w->mapToGlobal(local));
      QCursor::setPos(global);
      QMouseEvent mev(QEvent::MouseButtonRelease, local, global, toQtButton(args[4]), toQtButtonState(args[5]));
      qt_sendSpontaneousEvent(w, &mev);
      break;
    }

    case AQ::MouseButtonDblClick: {
      QPoint local(args[2].toInt(), args[3].toInt());
      QPoint global(w->mapToGlobal(local));
      QCursor::setPos(global);
      QMouseEvent mev(QEvent::MouseButtonDblClick, local, global, toQtButton(args[4]), toQtButtonState(args[5]));
      qt_sendSpontaneousEvent(w, &mev);
      break;
    }

    case AQ::MouseMove: {
      QPoint local(args[2].toInt(), args[3].toInt());
      QPoint global(w->mapToGlobal(local));
      QCursor::setPos(global);
      QMouseEvent mev(QEvent::MouseMove, local, global, toQtButton(args[4]), toQtButtonState(args[5]));
      qt_sendSpontaneousEvent(w, &mev);
      break;
    }

    case AQ::KeyPress:
    case AQ::KeyRelease: {
      int keyCode = args[2].toInt();
      QWidget *keywidget = QWidget::keyboardGrabber();
      bool grabbed = false;

      if (keywidget) {
        grabbed = true;
      } else {
        keywidget = focusWidget();
        if (!keywidget) {
          keywidget = activePopupWidget();
          if (!keywidget) {
            keywidget = activeWindow();
            if (!keywidget)
              keywidget = w->topLevelWidget();
          }
        }
      }

      if (keyCode < 0) {
        QKeyEvent kev((QEvent::Type) evT, 0, keyCode, toQtButtonState(args[3]), QChar(-keyCode));
        qt_sendSpontaneousEvent(keywidget, &kev);
      } else {
        if (evT == AQ::KeyPress && !grabbed) {
          QKeyEvent a((QEvent::Type) evT, toQtKey(keyCode), keyCode, toQtButtonState(args[3]));
          if (qt_tryAccelEvent(keywidget, &a))
            return;
        }
        QKeyEvent kev((QEvent::Type) evT, toQtKey(keyCode), keyCode, toQtButtonState(args[3]));
        qt_sendSpontaneousEvent(keywidget, &kev);
      }
      break;
    }

    case AQ::Move:
      if (w != desktop_) {
        ignoreEvents_ = true;
        w->move(args[2].toInt(), args[3].toInt());
        ignoreEvents_ = false;
      }
      break;

    case AQ::Resize:
      if (w != desktop_) {
        //ignoreEvents_ = true;
        w->resize(args[2].toInt(), args[3].toInt());
        //ignoreEvents_ = false;
      } else {
        int wt = args[2].toInt();
        int ht = args[3].toInt();
        desktopGeometry_.setRect(0, 0, wt, ht);
        desktop()->resize(wt, ht);
        postAQEvent(new AQEvent(w, new QResizeEvent(QSize(wt, ht), QSize())));
        emit desktop()->resized(0);
        if (!initDone_)
          QTimer::singleShot(0, this, SLOT(init()));
      }
      break;

    case AQ::XUpload: {
      QFileDialog *fd = ::qt_cast<QFileDialog *>(w);
      if (fd)
        fd->rereadDir();
      break;
    }

    case AQ::XProgressDialog: {
      uint pid = args[1].toUInt();
      if (args.size() == 2) {
        QProgressDialog *pd = progressDialogs_.take(pid);
        if (pd) {
          pd->close();
          pd->deleteLater();
        }
      } else {
        QProgressDialog *pd = progressDialogs_.find(pid);
        if (!pd) {
          pd = new QProgressDialog(args[2], QString(), args[3].section(';', 1, 1).toInt());
          progressDialogs_.insert(pid, pd);
        }
        pd->setProgress(args[3].section(';', 0, 0).toInt());
      }
      break;
    }

    case AQ::WindowStateChange: {
      w->setWindowState(args[2].toInt());
      break;
    }

    default: {
      QEvent ev((QEvent::Type) evT);
      qt_sendSpontaneousEvent(w, &ev);
    }
  }
}
Ejemplo n.º 11
0
void scan3d::reconstruct_model_simple(Pointcloud & pointcloud, CalibrationData const& calib, 
                                cv::Mat const& pattern_image, cv::Mat const& min_max_image, cv::Mat const& color_image,
                                cv::Size const& projector_size, int threshold, double max_dist, QWidget * parent_widget)
{
    if (!pattern_image.data || pattern_image.type()!=CV_32FC2)
    {   //pattern not correctly decoded
        std::cerr << "[reconstruct_model] ERROR invalid pattern_image\n";
        return;
    }
    if (!min_max_image.data || min_max_image.type()!=CV_8UC2)
    {   //pattern not correctly decoded
        std::cerr << "[reconstruct_model] ERROR invalid min_max_image\n";
        return;
    }
    if (color_image.data && color_image.type()!=CV_8UC3)
    {   //not standard RGB image
        std::cerr << "[reconstruct_model] ERROR invalid color_image\n";
        return;
    }
    if (!calib.is_valid())
    {   //invalid calibration
        return;
    }

    //parameters
    //const unsigned threshold = config.value("main/shadow_threshold", 70).toUInt();
    //const double   max_dist  = config.value("main/max_dist_threshold", 40).toDouble();
    //const bool     remove_background = config.value("main/remove_background", true).toBool();
    //const double   plane_dist = config.value("main/plane_dist", 100.0).toDouble();
    double plane_dist = 100.0;

    /* background removal
    cv::Point2i plane_coord[3];
    plane_coord[0] = cv::Point2i(config.value("background_plane/x1").toUInt(), config.value("background_plane/y1").toUInt());
    plane_coord[1] = cv::Point2i(config.value("background_plane/x2").toUInt(), config.value("background_plane/y2").toUInt());
    plane_coord[2] = cv::Point2i(config.value("background_plane/x3").toUInt(), config.value("background_plane/y3").toUInt());

    if (plane_coord[0].x<=0 || plane_coord[0].x>=pattern_local.cols
        || plane_coord[0].y<=0 || plane_coord[0].y>=pattern_local.rows)
    {
        plane_coord[0] = cv::Point2i(50, 50);
        config.setValue("background_plane/x1", plane_coord[0].x);
        config.setValue("background_plane/y1", plane_coord[0].y);
    }
    if (plane_coord[1].x<=0 || plane_coord[1].x>=pattern_local.cols
        || plane_coord[1].y<=0 || plane_coord[1].y>=pattern_local.rows)
    {
        plane_coord[1] = cv::Point2i(50, pattern_local.rows-50);
        config.setValue("background_plane/x2", plane_coord[1].x);
        config.setValue("background_plane/y2", plane_coord[1].y);
    }
    if (plane_coord[2].x<=0 || plane_coord[2].x>=pattern_local.cols
        || plane_coord[2].y<=0 || plane_coord[2].y>=pattern_local.rows)
    {
        plane_coord[2] = cv::Point2i(pattern_local.cols-50, 50);
        config.setValue("background_plane/x3", plane_coord[2].x);
        config.setValue("background_plane/y3", plane_coord[2].y);
    }
    */

    //init point cloud
    int scale_factor = 1;
    int out_cols = pattern_image.cols/scale_factor;
    int out_rows = pattern_image.rows/scale_factor;
    pointcloud.clear();
    pointcloud.init_points(out_rows, out_cols);
    pointcloud.init_color(out_rows, out_cols);

    //progress
    QProgressDialog * progress = NULL;
    if (parent_widget)
    {
        progress = new QProgressDialog("Reconstruction in progress.", "Abort", 0, pattern_image.rows, parent_widget, 
                                        Qt::Dialog|Qt::CustomizeWindowHint|Qt::WindowCloseButtonHint);
        progress->setWindowModality(Qt::WindowModal);
        progress->setWindowTitle("Processing");
        progress->setMinimumWidth(400);
    }

    //take 3 points in back plane
    /*cv::Mat plane;
    if (remove_background)
    {
        cv::Point3d p[3];
        for (unsigned i=0; i<3;i++)
        {
            for (unsigned j=0; 
                j<10 && (
                    INVALID(pattern_local.at<cv::Vec2f>(plane_coord[i].y, plane_coord[i].x)[0])
                    || INVALID(pattern_local.at<cv::Vec2f>(plane_coord[i].y, plane_coord[i].x)[1])); j++)
            {
                plane_coord[i].x += 1.f;
            }
            const cv::Vec2f & pattern = pattern_local.at<cv::Vec2f>(plane_coord[i].y, plane_coord[i].x);

            const float col = pattern[0];
            const float row = pattern[1];

            if (projector_size.width<=static_cast<int>(col) || projector_size.height<=static_cast<int>(row))
            {   //abort
                continue;
            }

            //shoot a ray through the image: u=\lambda*v + q
            cv::Point3d u1 = camera.to_world_coord(plane_coord[i].x, plane_coord[i].y);
            cv::Point3d v1 = camera.world_ray(plane_coord[i].x, plane_coord[i].y);

            //shoot a ray through the projector: u=\lambda*v + q
            cv::Point3d u2 = projector.to_world_coord(col, row);
            cv::Point3d v2 = projector.world_ray(col, row);

            //compute ray-ray approximate intersection
            double distance = 0.0;
            p[i] = geometry::approximate_ray_intersection(v1, u1, v2, u2, &distance);
            std::cout << "Plane point " << i << " distance " << distance << std::endl;
        }
        plane = geometry::get_plane(p[0], p[1], p[2]);
        if (cv::Mat(plane.rowRange(0,3).t()*cv::Mat(cv::Point3d(p[0].x, p[0].y, p[0].z-1.0)) + plane.at<double>(3,0)).at<double>(0,0)
                <0.0)
        {
            plane = -1.0*plane;
        }
        std::cout << "Background plane: " << plane << std::endl;
    }
    */

    cv::Mat Rt = calib.R.t();

    unsigned good = 0;
    unsigned bad  = 0;
    unsigned invalid = 0;
    unsigned repeated = 0;
    for (int h=0; h<pattern_image.rows; h+=scale_factor)
    {
        if (progress && h%4==0)
        {
            progress->setValue(h);
            progress->setLabelText(QString("Reconstruction in progress: %1 good points/%2 bad points").arg(good).arg(bad));
            QApplication::instance()->processEvents();
        }
        if (progress && progress->wasCanceled())
        {   //abort
            pointcloud.clear();
            return;
        }

        register const cv::Vec2f * curr_pattern_row = pattern_image.ptr<cv::Vec2f>(h);
        register const cv::Vec2b * min_max_row = min_max_image.ptr<cv::Vec2b>(h);
        for (register int w=0; w<pattern_image.cols; w+=scale_factor)
        {
            double distance = max_dist;  //quality meassure
            cv::Point3d p;               //reconstructed point
            //cv::Point3d normal(0.0, 0.0, 0.0);

            const cv::Vec2f & pattern = curr_pattern_row[w];
            const cv::Vec2b & min_max = min_max_row[w];

            if (sl::INVALID(pattern) || pattern[0]<0.f || pattern[1]<0.f
                || (min_max[1]-min_max[0])<static_cast<int>(threshold))
            {   //skip
                invalid++;
                continue;
            }

            const float col = pattern[0];
            const float row = pattern[1];

            if (projector_size.width<=static_cast<int>(col) || projector_size.height<=static_cast<int>(row))
            {   //abort
                continue;
            }

            cv::Vec3f & cloud_point = pointcloud.points.at<cv::Vec3f>(h/scale_factor, w/scale_factor);
            if (!sl::INVALID(cloud_point[0]))
            {   //point already reconstructed!
                repeated++;
                continue;
            }

            //standard
            cv::Point2d p1(w, h);
            cv::Point2d p2(col, row);
            triangulate_stereo(calib.cam_K, calib.cam_kc, calib.proj_K, calib.proj_kc, Rt, calib.T, p1, p2, p, &distance);

            //save texture coordinates
            /*
            normal.x = static_cast<float>(w)/static_cast<float>(color_image.cols);
            normal.y = static_cast<float>(h)/static_cast<float>(color_image.rows);
            normal.z = 0;
            */

            if (distance < max_dist)
            {   //good point

                //evaluate the plane
                double d = plane_dist+1;
                /*if (remove_background)
                {
                    d = cv::Mat(plane.rowRange(0,3).t()*cv::Mat(p) + plane.at<double>(3,0)).at<double>(0,0);
                }*/
                if (d>plane_dist)
                {   //object point, keep
                    good++;

                    cloud_point[0] = p.x;
                    cloud_point[1] = p.y;
                    cloud_point[2] = p.z;

                    //normal
                    /*cpoint.normal_x = normal.x;
                    cpoint.normal_y = normal.y;
                    cpoint.normal_z = normal.z;*/

                    if (color_image.data)
                    {
                        const cv::Vec3b & vec = color_image.at<cv::Vec3b>(h, w);
                        cv::Vec3b & cloud_color = pointcloud.colors.at<cv::Vec3b>(h/scale_factor, w/scale_factor);
                        cloud_color[0] = vec[0];
                        cloud_color[1] = vec[1];
                        cloud_color[2] = vec[2];
                    }
                }
            }
            else
            {   //skip
                bad++;
                //std::cout << " d = " << distance << std::endl;
            }
        }   //for each column
    }   //for each row

    if (progress)
    {
        progress->setValue(pattern_image.rows);
        progress->close();
        delete progress;
        progress = NULL;
    }

    std::cout << "Reconstructed points[simple]: " << good << " (" << bad << " skipped, " << invalid << " invalid) " << std::endl
                << " - repeated points: " << repeated << " (ignored) " << std::endl;
}
Ejemplo n.º 12
0
void inputRZImpl::print()
{
    QString fname = EGSdir + EGSfileName;
    QPrinter* printer = new QPrinter;
    printer->setPageSize( QPrinter::Letter );
    const int Margin = 20;
    const int MarginY = 30;
    int pageNo = 1;

    QPrintDialog pdialog(printer,this);

    if ( pdialog.exec()) {

cout << "let's print !!!" << endl;


        QPainter paint( printer );
        //if( !paint.begin( printer ) )              // paint on printer
        //     return;

       static const char *fonts[] = { "Helvetica", "Courier", "Times", 0 };
       static int	 sizes[] = { 10, 12, 18, 24, 36, 0 };
       int yPos = 0;

       QFont fontNormal( fonts[1], sizes[0] );
       QFont fontBold( fonts[0], sizes[0] );
       fontBold.setWeight( QFont::Black);

       paint.setFont( fontBold );
       QFontMetrics fmBold = paint.fontMetrics();
       paint.setFont( fontNormal );
       QFontMetrics fm = paint.fontMetrics();

       //qt3to4 -- BW
       //Q3PaintDeviceMetrics metrics( printer ); // need width/height

       QFile              fi( fname );
       //qt3to4 -- BW
       //Q3TextStream ts( &fi );
       QTextStream ts( &fi );
       QString          t;
       int StepsPerPage =  500;

       int LinesPerPage = (printer->height() - 2* MarginY) / fm.lineSpacing();
       if ( fi.open( QIODevice::ReadOnly ) ) {

            int NumOfPages = 1 + TotalTextLines( fname ) / LinesPerPage;
            int totalSteps = StepsPerPage * NumOfPages;

            QString msg( "Printing (page " );
                         msg += QString::number( pageNo );
                         msg += ")...";
            //qt3to4 -- BW
            //Q3ProgressDialog* dialog = new Q3ProgressDialog(msg, "Cancel",
             //                                                               totalSteps, this, "progress", true);
            QProgressDialog* dialog = new QProgressDialog(msg, "Cancel",0,totalSteps);
            //dialog->setTotalSteps( totalSteps );
            //dialog->setProgress( 0 );
            dialog->setValue(0);
            dialog->setMinimumDuration( 0 );

            int progress_count = 0;

           QString gui = "EGSnrc GUI for RZ Geometries:  " + EGSfileName;
           QDate currDate = QDate::currentDate();
           QString date = currDate.toString ( "dd.MM.yyyy" );
           paint.setFont( fontBold );
           paint.drawText( Margin, 0,  printer->width() - 2*Margin, fmBold.lineSpacing(),
                        Qt::AlignLeft | Qt::RichText, gui );
           paint.drawText( Margin, 0,  printer->width() - 2*Margin, fmBold.lineSpacing(),
                        Qt::AlignRight, date );
           paint.drawLine( Margin, MarginY - 10, printer->width() - Margin, MarginY - 10 );
           paint.drawLine( Margin, printer->height() - MarginY + 10,
                                    printer->width() - Margin, printer->height() - MarginY + 10 );
           paint.drawText( Margin, printer->height() - fmBold.lineSpacing(),
	                       printer->width(), fmBold.lineSpacing(),
                                     Qt::AlignHCenter, QString::number( pageNo ) );
           paint.setFont( fontNormal );

           do {
                progress_count++;
                qApp->processEvents();
                if ( dialog->wasCanceled() )
                     dialog->close();
                t = ts.readLine();

                if ( MarginY + yPos + fm.lineSpacing() > printer->height() - MarginY ) {
                         do{
                                    //dialog->setProgress( ++progress_count );
                                    dialog->setValue(++progress_count );
                         }while ( progress_count < StepsPerPage*pageNo );
	           msg = "Printing (page " + QString::number( ++pageNo ) + ")...";
	           dialog->setLabelText( msg );
                         printer->newPage();             // no more room on this page
                         yPos = 0;                       // back to top of page
                         paint.setFont( fontBold );
                         paint.drawText( Margin, 0,  printer->width() - 2*Margin, fmBold.lineSpacing(),
                                                   Qt::AlignLeft | Qt::RichText, gui );
                         paint.drawText( Margin, 0,  printer->width() - 2*Margin, fmBold.lineSpacing(),
                                                  Qt::AlignRight, date );
                        paint.drawLine( Margin, MarginY - 10, printer->width() - Margin, MarginY - 10 );
	          paint.drawLine( Margin, printer->height() - MarginY + 10,
                                    printer->width() - Margin, printer->height() - MarginY + 10 );
                        paint.drawText( Margin, printer->height() - fmBold.lineSpacing(),
	                       printer->width(), fmBold.lineSpacing(),
                                     Qt::AlignHCenter, QString::number( pageNo ) );
                         paint.setFont( fontNormal );
                }

                paint.drawText( Margin, MarginY + yPos,
                        printer->width(), fm.lineSpacing(),
                        Qt::TextExpandTabs | Qt::TextDontClip, t );

                yPos = yPos + fm.lineSpacing();

               dialog->setValue( progress_count );

           //qt3to4 -- BW
           //} while ( !ts.eof() );
          } while ( !ts.atEnd() );

          do{
               dialog->setValue( ++progress_count );
           }while ( progress_count < totalSteps );

          dialog->setValue( totalSteps );
          zap(dialog);
       }
       else {
               QMessageBox::critical( 0,
                        tr("Error printing "),
	          tr("Couldn't open file %1").arg(fname),
                        tr("Quit") );
       }

       fi.close();

    }
    else {
             QMessageBox::information( this, "Printing status", "Printing aborted");
    }

    delete printer;
}
Ejemplo n.º 13
0
void Uploading::uploadingProcess(const QString &actionId)
{
	{
		QProgressDialog progressDialog;
		progressDialog.setWindowModality(Qt::WindowModal);
		progressDialog.setWindowTitle(tr("Выгрузка базы данных"));
		progressDialog.setLabelText(tr("Процесс выгрузки базы данных"));
		progressDialog.setCancelButton(0);
		progressDialog.setMinimumDuration(0);
		progressDialog.setMaximum(6);
		progressDialog.setValue(0);

		QSqlDatabase db = QSqlDatabase::database(UPLOADING);
		createDBScheme();

		progressDialog.setValue(1);
		QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);

		QSqlQuery selectDataQuery(QSqlDatabase::database(mConnection));
		QSqlQuery insertDataQuery(db);

		if(selectDataQuery.exec("SELECT id, title, performer FROM Actions WHERE id = " + actionId))
		{
			insertDataQuery.prepare("INSERT INTO Actions VALUES(:id, :title, :performer);");
			while(selectDataQuery.next())
			{
				insertDataQuery.bindValue(":id", selectDataQuery.value(0));
				insertDataQuery.bindValue(":title", selectDataQuery.value(1));
				insertDataQuery.bindValue(":performer", selectDataQuery.value(2));
				insertDataQuery.exec();
			}
		}

		progressDialog.setValue(2);

		QList<int> placeSchemeIds;
		QList<int> clientIds;

		if(selectDataQuery.exec("SELECT id, id_action, id_placeScheme, id_client, identifier FROM Tickets WHERE id_action = " + actionId))
		{
			insertDataQuery.prepare("INSERT INTO Tickets VALUES(NULL, :id_action, :id_placeScheme, :id_client, :identifier, :passedFlag);");
			while(selectDataQuery.next())
			{
				insertDataQuery.bindValue(":id_action", selectDataQuery.value(1));
				insertDataQuery.bindValue(":id_placeScheme", selectDataQuery.value(2));
				insertDataQuery.bindValue(":id_client", selectDataQuery.value(3));
				insertDataQuery.bindValue(":identifier", selectDataQuery.value(4));
				insertDataQuery.bindValue(":passedFlag", "false");
				insertDataQuery.exec();

				if(selectDataQuery.isNull(2) == false)
					placeSchemeIds.append(selectDataQuery.value(2).toInt());

				if(selectDataQuery.isNull(3) == false)
					clientIds.append(selectDataQuery.value(4).toInt());
			}
		}

		progressDialog.setValue(3);

		if(placeSchemeIds.isEmpty() == false)
		{
			if(selectDataQuery.exec("SELECT id, seatNumber, row FROM PlaceSchemes"))
			{
				insertDataQuery.prepare("INSERT INTO PlaceSchemes VALUES(:id, :seatNumber, :row)");
				while(selectDataQuery.next())
				{
					if(placeSchemeIds.contains( selectDataQuery.value(0).toInt()) )
					{
						insertDataQuery.bindValue(":id", selectDataQuery.value(0));
						insertDataQuery.bindValue(":seatNumber", selectDataQuery.value(1));
						insertDataQuery.bindValue(":row", selectDataQuery.value(2));
						insertDataQuery.exec();
					}
				}
			}
		}

		progressDialog.setValue(4);

		if(clientIds.isEmpty() == false)
		{
			if(selectDataQuery.exec("SELECT id, name, login FROM Clients"))
			{
				insertDataQuery.prepare("INSERT INTO Clients VALUES(:id, :name, :login)");
				while(selectDataQuery.next())
				{
					if(clientIds.contains( selectDataQuery.value(0).toInt() ))
					{
						insertDataQuery.bindValue(":id", selectDataQuery.value(0));
						insertDataQuery.bindValue(":name", selectDataQuery.value(1));
						insertDataQuery.bindValue(":login", selectDataQuery.value(2));
						insertDataQuery.exec();
					}
				}
			}
		}

		progressDialog.setValue(5);

		if(selectDataQuery.exec("SELECT id, id_client, identifier FROM ReturnedTickets WHERE id_action = " + actionId))
		{
			insertDataQuery.prepare("INSERT INTO ReturnedTickets VALUES(NULL, :id_client, :identifier);");
			while(selectDataQuery.next())
			{
				insertDataQuery.bindValue(":id_client", selectDataQuery.value(1));
				insertDataQuery.bindValue(":identifier", selectDataQuery.value(2));
				insertDataQuery.exec();
			}
		}

		progressDialog.setValue(6);
		progressDialog.close();
		db.close();
	}
	QSqlDatabase::removeDatabase(UPLOADING);
}
Ejemplo n.º 14
0
void MainWindow::on_computeButton_clicked()
{
    //disabling actions that could make the application crash
    ui->openButton->setEnabled(false);
    ui->computeButton->setEnabled(false);

    QPrincipalAxisGenerator generator;

    if( computedMeshes ){
        //cleaning previous calculation
        for( int i=1;i<nViewers; i++ ){
            leftWidgets[i]->deleteMeshes();
            rightWidgets[i]->deleteMeshes();
        }
    }

    vector<Method> methods2compute;
    //add them in the order of the tabs
    methods2compute.push_back( JUST_PCA );
    methods2compute.push_back( ROBUS_DETERMINATION );

    int progressIt=0;

    QProgressDialog progress;
    progress.setWindowTitle("Loading");
    progress.setLabelText("Computing meshes...");
    progress.setCancelButton(NULL);
    progress.setMinimum(0);
    progress.setMaximum(100);
    progress.show();

    for( int i=0; i< leftWidgets[0]->getNumberOfMeshes(); i++ ){

        generator.setMesh( leftWidgets[0]->getMesh(i) );

        for( int j=0; j<methods2compute.size(); j++ ){

            generator.setMethod( methods2compute.at(j) );//selecting method to generate axis

            generator.start();//computing on other thread not to freeze the main window

            while(generator.isRunning()){
                //forcing window refresh events so the window not freezes during the wait
                qApp->processEvents();
                update();
                repaint();
                ui->centralWidget->repaint();
            }
            //tab position, 0 is the original tab
            leftWidgets[j+1]->insert_mesh( leftWidgets[0]->getMesh(i),generator.getAxis() );
            rightWidgets[j+1]->insert_mesh( rightWidgets[0]->getMesh(i),generator.getAxis() );

            leftWidgets[j+1]->setMeshVisiblility( i,leftWidgets[0]->isMeshVisible(i) );
            rightWidgets[j+1]->setMeshVisiblility( i,leftWidgets[0]->isMeshVisible(i) );


            progressIt++;
            progress.setValue( progressIt*100/(leftWidgets[0]->getNumberOfMeshes()*2) );
            progress.update();
        }
        /*
         //stating way, just for debuging
        generator.setMethod( JUST_PCA );//selecting method to generate axis

        generator.start();//computing on other thread not to freeze the main window

        while(generator.isRunning()){
            //forcing window refresh events so the window not freezes during the wait
            qApp->processEvents();
            update();
            repaint();
            ui->centralWidget->repaint();
        }

        leftWidgets[1]->insert_mesh( leftWidgets[0]->getMesh(i),generator.getAxis() );
        rightWidgets[1]->insert_mesh( rightWidgets[0]->getMesh(i),generator.getAxis() );

        leftWidgets[1]->setMeshVisiblility( i,leftWidgets[0]->isMeshVisible(i) );
        rightWidgets[1]->setMeshVisiblility( i,leftWidgets[0]->isMeshVisible(i) );


        progressIt++;
        progress.setValue( progressIt*100/(leftWidgets[0]->getNumberOfMeshes()*2) );
        progress.update();
        //sleep(2);

        generator.setMethod( ROBUS_DETERMINATION );
        generator.start();

        while(generator.isRunning()){
            //forcing window refresh events so the window not freezes during the wait
            qApp->processEvents();
            update();
            repaint();
            ui->centralWidget->repaint();
        }


        leftWidgets[2]->insert_mesh( leftWidgets[0]->getMesh(i),generator.getAxis() );
        rightWidgets[2]->insert_mesh( rightWidgets[0]->getMesh(i),generator.getAxis() );


        leftWidgets[2]->setMeshVisiblility( i,leftWidgets[0]->isMeshVisible(i) );
        rightWidgets[2]->setMeshVisiblility( i,leftWidgets[0]->isMeshVisible(i) );

        progressIt++;
        progress.setValue( progressIt*100/(leftWidgets[0]->getNumberOfMeshes()*2) );
        progress.update();
        */
        //sleep(2);
    }

    progress.setValue(100);
    progress.close();

    //apply translation and rotation

    cout <<"Computing axis completed"<<endl;
    computedMeshes=true;
    ui->openButton->setEnabled(true);
    ui->computeButton->setEnabled(true);
    ui->alignButton->setEnabled(true);
}