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; }
int main(int argc, char *argv[]) { QApplication app(argc, argv); //application settings app.setOrganizationName(QLatin1String("TestSoftware")); app.setOrganizationDomain(QLatin1String("testsoft.com")); app.setApplicationName(QLatin1String("TestGraphs")); app.setApplicationVersion(QLatin1String("1.0")); //qml loading MainQmlQuick1Loader view; TranslationChanger translationChanger; view.setMainTranslator(&translationChanger); view.createLangMenu(); QProgressDialog *mainProgressDialog = new QProgressDialog(&view, Qt::FramelessWindowHint); mainProgressDialog->setWindowModality(Qt::WindowModal); static const QString cancelButtonStr = QObject::tr("Cancel"); mainProgressDialog->setCancelButtonText(cancelButtonStr); qmlRegisterType<GraphsAlgorithmsSolver>("com.testsoft.graphs", 1, 0, "GraphSolver"); view.rootContext()->setContextProperty(QLatin1String("mainTranslator"), (QObject *) &translationChanger); view.rootContext()->setContextProperty(QLatin1String("mainProgressDialog"), (QObject *) mainProgressDialog); view.setResizeMode(QDeclarativeView::SizeRootObjectToView); view.setMainQmlFile(QLatin1String("qrc:////MainFilePath/main.qml")); view.showQmlScene(); return app.exec(); }
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; }
/*========================================================================= 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); }
void MainWindow::openFile() { QString newFile = QFileDialog::getOpenFileName(this, tr("Open SQL File"), QDir::currentPath(), tr("SQL file (*.sql);;All Files (*)")); if (newFile.isNull()) return; QFile f(newFile); if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::warning(this, tr("Open SQL Script"), tr("Cannot open file %1").arg(newFile)); return; } int prgTmp = 0; QProgressDialog * progress = new QProgressDialog(tr("Opening: %1").arg(newFile), tr("Abort"), 0, f.size(), this); connect(progress, SIGNAL(canceled()), this, SLOT(cancel())); progress->setWindowModality(Qt::WindowModal); progress->setMinimumDuration(1000); SqlViewWidget *newSqlview = new SqlViewWidget(); QFileInfo pathInfo(newFile); sqlViewWidget->addTab(newSqlview,pathInfo.fileName()); sqlViewWidget->setCurrentWidget(newSqlview); newSqlview->sqlInput->clear(); QTextStream in(&f); QString line; QStringList strList; while (!in.atEnd()) { line = in.readLine(); strList.append(line); prgTmp += line.length(); } f.close(); progress->setLabelText(tr("Formatting the text. Please wait.")); newSqlview->sqlInput->append(strList.join("\n")); newSqlview->sqlInput->setModified(false); delete progress; progress = 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); }
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(); }
void ConfigDialog::devpairClicked() { DeviceConfiguration add; // get values from the gui elements add.name = devicePage->deviceName->displayText(); add.type = devicePage->typeSelector->itemData(devicePage->typeSelector->currentIndex()).toInt(); add.portSpec = devicePage->deviceSpecifier->displayText(); add.deviceProfile = devicePage->deviceProfile->displayText(); QProgressDialog *progress = new QProgressDialog("Looking for Devices...", "Abort Scan", 0, 200, this); progress->setWindowModality(Qt::WindowModal); devicePage->pairClicked(&add, progress); }
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(); }
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(); }
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 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(); }
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; }
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; }
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; }
// Refresh not up to date metrics and metrics after date void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate) { // only if we have established a connection to the database if (dbaccess == NULL || context->athlete->isclean==true) return; // first check db structure is still up to date // this is because metadata.xml may add new fields dbaccess->checkDBVersion(); // Get a list of the ride files QRegExp rx = RideFileFactory::instance().rideFileRegExp(); QStringList filenames = RideFileFactory::instance().listRideFiles(context->athlete->home); QStringListIterator i(filenames); // get a Hash map of statistic records and timestamps QSqlQuery query(dbaccess->connection()); QHash <QString, status> dbStatus; bool rc = query.exec("SELECT filename, timestamp, fingerprint FROM metrics ORDER BY ride_date;"); while (rc && query.next()) { status add; QString filename = query.value(0).toString(); add.timestamp = query.value(1).toInt(); add.fingerprint = query.value(2).toInt(); dbStatus.insert(filename, add); } // begin LUW -- byproduct of turning off sync (nosync) dbaccess->connection().transaction(); // Delete statistics for non-existant ride files QHash<QString, status>::iterator d; for (d = dbStatus.begin(); d != dbStatus.end(); ++d) { if (QFile(context->athlete->home.absolutePath() + "/" + d.key()).exists() == false) { dbaccess->deleteRide(d.key()); #ifdef GC_HAVE_LUCENE context->athlete->lucene->deleteRide(d.key()); #endif } } unsigned long zoneFingerPrint = static_cast<unsigned long>(context->athlete->zones()->getFingerprint()) + static_cast<unsigned long>(context->athlete->hrZones()->getFingerprint()); // checksum of *all* zone data (HR and Power) // update statistics for ride files which are out of date // showing a progress bar as we go QTime elapsed; elapsed.start(); QString title = tr("Updating Statistics\nStarted"); QProgressDialog *bar = NULL; int processed=0; QApplication::processEvents(); // get that dialog up! // log of progress QFile log(context->athlete->home.absolutePath() + "/" + "metric.log"); log.open(QIODevice::WriteOnly); log.resize(0); QTextStream out(&log); out << "METRIC REFRESH STARTS: " << QDateTime::currentDateTime().toString() + "\r\n"; while (i.hasNext()) { QString name = i.next(); QFile file(context->athlete->home.absolutePath() + "/" + name); // if it s missing or out of date then update it! status current = dbStatus.value(name); unsigned long dbTimeStamp = current.timestamp; unsigned long fingerprint = current.fingerprint; RideFile *ride = NULL; processed++; // create the dialog if we need to show progress for long running uodate long elapsedtime = elapsed.elapsed(); if ((first || elapsedtime > 6000) && bar == NULL) { bar = new QProgressDialog(title, tr("Abort"), 0, filenames.count()); // not owned by mainwindow bar->setWindowFlags(bar->windowFlags() | Qt::FramelessWindowHint); bar->setWindowModality(Qt::WindowModal); bar->setMinimumDuration(0); bar->show(); // lets hide until elapsed time is > 6 seconds } // update the dialog always after 6 seconds if (first || elapsedtime > 6000) { // update progress bar QString elapsedString = QString("%1:%2:%3").arg(elapsedtime/3600000,2) .arg((elapsedtime%3600000)/60000,2,10,QLatin1Char('0')) .arg((elapsedtime%60000)/1000,2,10,QLatin1Char('0')); QString title = tr("%1\n\nUpdate Statistics\nElapsed: %2\n\n%3").arg(context->athlete->cyclist).arg(elapsedString).arg(name); bar->setLabelText(title); bar->setValue(processed); } QApplication::processEvents(); if (dbTimeStamp < QFileInfo(file).lastModified().toTime_t() || zoneFingerPrint != fingerprint || (!forceAfterThisDate.isNull() && name >= forceAfterThisDate.toString("yyyy_MM_dd_hh_mm_ss"))) { QStringList errors; // log out << "Opening ride: " << name << "\r\n"; // read file and process it if we didn't already... if (ride == NULL) ride = RideFileFactory::instance().openRideFile(context, file, errors); out << "File open completed: " << name << "\r\n"; if (ride != NULL) { out << "Getting weight: " << name << "\r\n"; ride->getWeight(); out << "Updating statistics: " << name << "\r\n"; importRide(context->athlete->home, ride, name, zoneFingerPrint, (dbTimeStamp > 0)); } } // update cache (will check timestamps itself) // if ride wasn't opened it will do it itself // we only want to check so passing check=true // because we don't actually want the results now RideFileCache updater(context, context->athlete->home.absolutePath() + "/" + name, ride, true); // free memory - if needed if (ride) delete ride; if (bar && bar->wasCanceled()) { out << "METRIC REFRESH CANCELLED\r\n"; break; } } // now zap the progress bar if (bar) delete bar; // end LUW -- now syncs DB out << "COMMIT: " << QDateTime::currentDateTime().toString() + "\r\n"; dbaccess->connection().commit(); #ifdef GC_HAVE_LUCENE #ifndef WIN32 // windows crashes here.... out << "OPTIMISE: " << QDateTime::currentDateTime().toString() + "\r\n"; context->athlete->lucene->optimise(); #endif #endif context->athlete->isclean = true; // stop logging out << "SIGNAL DATA CHANGED: " << QDateTime::currentDateTime().toString() + "\r\n"; dataChanged(); // notify models/views out << "METRIC REFRESH ENDS: " << QDateTime::currentDateTime().toString() + "\r\n"; log.close(); first = false; }
void QgsTINInterpolator::initialize() { DualEdgeTriangulation* theDualEdgeTriangulation = new DualEdgeTriangulation( 100000, 0 ); if ( mInterpolation == CloughTocher ) { NormVecDecorator* dec = new NormVecDecorator(); dec->addTriangulation( theDualEdgeTriangulation ); mTriangulation = dec; } else { mTriangulation = theDualEdgeTriangulation; } //get number of features if we use a progress bar int nFeatures = 0; int nProcessedFeatures = 0; if ( mShowProgressDialog ) { QList<LayerData>::iterator layerDataIt = mLayerData.begin(); for ( ; layerDataIt != mLayerData.end(); ++layerDataIt ) { if ( layerDataIt->vectorLayer ) { nFeatures += layerDataIt->vectorLayer->featureCount(); } } } QProgressDialog* theProgressDialog = 0; if ( mShowProgressDialog ) { theProgressDialog = new QProgressDialog( QObject::tr( "Building triangulation..." ), QObject::tr( "Abort" ), 0, nFeatures, 0 ); theProgressDialog->setWindowModality( Qt::WindowModal ); } QgsFeature f; QList<LayerData>::iterator layerDataIt = mLayerData.begin(); for ( ; layerDataIt != mLayerData.end(); ++layerDataIt ) { if ( layerDataIt->vectorLayer ) { QgsAttributeList attList; if ( !layerDataIt->zCoordInterpolation ) { attList.push_back( layerDataIt->interpolationAttribute ); } QgsFeatureIterator fit = layerDataIt->vectorLayer->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( attList ) ); while ( fit.nextFeature( f ) ) { if ( mShowProgressDialog ) { if ( theProgressDialog->wasCanceled() ) { break; } theProgressDialog->setValue( nProcessedFeatures ); } insertData( &f, layerDataIt->zCoordInterpolation, layerDataIt->interpolationAttribute, layerDataIt->mInputType ); ++nProcessedFeatures; } } } delete theProgressDialog; if ( mInterpolation == CloughTocher ) { CloughTocherInterpolator* ctInterpolator = new CloughTocherInterpolator(); NormVecDecorator* dec = dynamic_cast<NormVecDecorator*>( mTriangulation ); if ( dec ) { QProgressDialog* progressDialog = 0; if ( mShowProgressDialog ) //show a progress dialog because it can take a long time... { progressDialog = new QProgressDialog(); progressDialog->setLabelText( QObject::tr( "Estimating normal derivatives..." ) ); } dec->estimateFirstDerivatives( progressDialog ); delete progressDialog; ctInterpolator->setTriangulation( dec ); dec->setTriangleInterpolator( ctInterpolator ); mTriangleInterpolator = ctInterpolator; } } else //linear { mTriangleInterpolator = new LinTriangleInterpolator( theDualEdgeTriangulation ); } mIsInitialized = true; //debug if ( mExportTriangulationToFile ) { theDualEdgeTriangulation->saveAsShapefile( mTriangulationFilePath ); } }
void createFakeData() { QStringList names; names << "Eabha Biddell" << "Prentice Hutchison" << "Rameesha Davidge" << "Digby Roson" << "Nettah Newarch" << "Lewisha Middleton" << "Ahmed Hanmer" << "Jordyn-Leigh Lamant" << "Lindsay Bigham" << "Kaylay Weir" << "Sofia Weir" << "Coel Spurlock" << "Youcef Culpan" << "Lucy-Jasmine Blanchard" << "Ally Hodgkin" << "Ara Collinge" << "Luka Dempster" << "Samanta Winster" << "Keri Palin" << "Ruiridh Bisset" << "Norman Epworth" << "Kezia Raw" << "Kaylan-Thomas Swynford" << "Kashaf Benning" << "Norma Yair" << "Edan Bassett" << "Akshat Mcglasson" << "Philippa Upton" << "Tylor Rockliff" << "Aqdas Buckman" << "Briana Dowell" << "Querida North" << "Chelsay Botts" << "Kishanth Calloway" << "Jan Covington" << "Teighan Monson" << "Claudia Mendel" << "Kerra Doe" << "Kara Depp" << "Harlie Soole" << "Viggo Streeter" << "Ava Cofel" << "Catherine Balderston" << "Brendan Gosnay" << "Zhaoyun Haygarth" << "Deri Pepler" << "Vicki Hopwood" << "Amitra Bindless" << "Cerhys Hayton" << "Gwendoline Westall"; QProgressDialog progress; progress.setWindowModality(Qt::WindowModal); progress.setWindowTitle(QObject::tr("Staff Manager")); progress.setLabelText(QObject::tr("Creating database...")); progress.setMinimum(0); progress.setMaximum(names.count() + 6); progress.setValue(1); qApp->processEvents(); QSqlQuery query; query.exec("DROP TABLE department"); query.exec("DROP TABLE employee"); query.exec("DROP TABLE location"); progress.setValue(2); qApp->processEvents(); query.exec("CREATE TABLE location (" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "name VARCHAR(40) NOT NULL)"); progress.setValue(3); qApp->processEvents(); query.exec("CREATE TABLE department (" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "name VARCHAR(40) NOT NULL, " "locationid INTEGER NOT NULL, " "FOREIGN KEY (locationid) REFERENCES location)"); progress.setValue(4); qApp->processEvents(); query.exec("CREATE TABLE employee (" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "name VARCHAR(40) NOT NULL, " "departmentid INTEGER NOT NULL, " "extension INTEGER NOT NULL, " "email VARCHAR(40) NOT NULL, " "startdate DATE NOT NULL, " "FOREIGN KEY (departmentid) REFERENCES department)"); progress.setValue(5); qApp->processEvents(); query.exec("INSERT INTO location (name) VALUES (" "'Floor 18, 1129 Evanston Heights, New York, NY')"); query.exec("INSERT INTO location (name) VALUES (" "'The Shed, Elmtree Drive, Boston, MA')"); query.exec("INSERT INTO location (name) VALUES (" "'14 Valentine Buildings, Amor Street, Cambridge, MA')"); query.exec("INSERT INTO location (name) VALUES (" "'Bunker Building, Silo Avenue, Los Angeles, CA')"); query.exec("INSERT INTO department (name, locationid) VALUES (" "'Sales', 1)"); query.exec("INSERT INTO department (name, locationid) VALUES (" "'Marketing', 2)"); query.exec("INSERT INTO department (name, locationid) VALUES (" "'Processing', 1)"); query.exec("INSERT INTO department (name, locationid) VALUES (" "'Support', 4)"); query.exec("INSERT INTO department (name, locationid) VALUES (" "'Research', 3)"); progress.setValue(6); qApp->processEvents(); int count = 0; query.prepare("INSERT INTO employee (name, departmentid, " "extension, email, startdate) " "VALUES (:name, :departmentid, :extension, " ":email, :startdate)"); foreach (QString name, names) { query.bindValue(":name", name); query.bindValue(":departmentid", 1 + (std::rand() % 5)); query.bindValue(":extension", 400 + (std::rand() % 100)); query.bindValue(":email", name.toLower().replace(" ", ".") + "@company.com"); query.bindValue(":startdate", QDate::currentDate().addDays(-(std::rand() % 3600))); query.exec(); ++count; progress.setValue(count + 6); }
int QgsWFSData::getWFSData() { XML_Parser p = XML_ParserCreateNS( NULL, NS_SEPARATOR ); XML_SetUserData( p, this ); XML_SetElementHandler( p, QgsWFSData::start, QgsWFSData::end ); XML_SetCharacterDataHandler( p, QgsWFSData::chars ); //start with empty extent if ( mExtent ) { mExtent->set( 0, 0, 0, 0 ); } //QUrl requestUrl( mUri ); QNetworkRequest request( mUri ); QNetworkReply* reply = QgsNetworkAccessManager::instance()->get( request ); connect( reply, SIGNAL( finished() ), this, SLOT( setFinished() ) ); connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( handleProgressEvent( qint64, qint64 ) ) ); //find out if there is a QGIS main window. If yes, display a progress dialog QProgressDialog* progressDialog = 0; QWidget* mainWindow = findMainWindow(); if ( mainWindow ) { progressDialog = new QProgressDialog( tr( "Loading WFS data\n%1" ).arg( mTypeName ), tr( "Abort" ), 0, 0, mainWindow ); progressDialog->setWindowModality( Qt::ApplicationModal ); connect( this, SIGNAL( dataReadProgress( int ) ), progressDialog, SLOT( setValue( int ) ) ); connect( this, SIGNAL( totalStepsUpdate( int ) ), progressDialog, SLOT( setMaximum( int ) ) ); connect( progressDialog, SIGNAL( canceled() ), this, SLOT( setFinished() ) ); progressDialog->show(); } int atEnd = 0; while ( !atEnd ) { if ( mFinished ) { atEnd = 1; } QByteArray readData = reply->readAll(); if ( readData.size() > 0 ) { XML_Parse( p, readData.constData(), readData.size(), atEnd ); } QCoreApplication::processEvents(); } delete reply; delete progressDialog; if ( mExtent ) { if ( mExtent->isEmpty() ) { //reading of bbox from the server failed, so we calculate it less efficiently by evaluating the features calculateExtentFromFeatures(); } } XML_ParserFree( p ); return 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; }
int QgsGridFileWriter::writeFile( bool showProgressDialog ) { QFile outputFile( mOutputFilePath ); if ( !outputFile.open( QFile::WriteOnly ) ) { return 1; } if ( !mInterpolator ) { outputFile.remove(); return 2; } QTextStream outStream( &outputFile ); outStream.setRealNumberPrecision( 8 ); writeHeader( outStream ); double currentYValue = mInterpolationExtent.yMaximum() - mCellSizeY / 2.0; //calculate value in the center of the cell double currentXValue; double interpolatedValue; QProgressDialog* progressDialog = 0; if ( showProgressDialog ) { progressDialog = new QProgressDialog( QObject::tr( "Interpolating..." ), QObject::tr( "Abort" ), 0, mNumRows, 0 ); progressDialog->setWindowModality( Qt::WindowModal ); } for ( int i = 0; i < mNumRows; ++i ) { currentXValue = mInterpolationExtent.xMinimum() + mCellSizeX / 2.0; //calculate value in the center of the cell for ( int j = 0; j < mNumColumns; ++j ) { if ( mInterpolator->interpolatePoint( currentXValue, currentYValue, interpolatedValue ) == 0 ) { outStream << interpolatedValue << ' '; } else { outStream << "-9999 "; } currentXValue += mCellSizeX; } outStream << endl; currentYValue -= mCellSizeY; if ( showProgressDialog ) { if ( progressDialog->wasCanceled() ) { outputFile.remove(); return 3; } progressDialog->setValue( i ); } } // create prj file QgsInterpolator::LayerData ld; ld = mInterpolator->layerData().first(); QgsVectorLayer* vl = ld.vectorLayer; QString crs = vl->crs().toWkt(); QFileInfo fi( mOutputFilePath ); QString fileName = fi.absolutePath() + '/' + fi.completeBaseName() + ".prj"; QFile prjFile( fileName ); if ( !prjFile.open( QFile::WriteOnly ) ) { return 1; } QTextStream prjStream( &prjFile ); prjStream << crs; prjStream << endl; prjFile.close(); delete progressDialog; return 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); }
int QgsGridFileWriter::writeFile( bool showProgressDialog ) { QFile outputFile( mOutputFilePath ); if ( !outputFile.open( QFile::WriteOnly ) ) { return 1; } if ( !mInterpolator ) { outputFile.remove(); return 2; } QTextStream outStream( &outputFile ); outStream.setRealNumberPrecision( 8 ); writeHeader( outStream ); double currentYValue = mInterpolationExtent.yMaximum() - mCellSizeY / 2.0; //calculate value in the center of the cell double currentXValue; double interpolatedValue; QProgressDialog* progressDialog = 0; if ( showProgressDialog ) { progressDialog = new QProgressDialog( QObject::tr( "Interpolating..." ), QObject::tr( "Abort" ), 0, mNumRows, 0 ); progressDialog->setWindowModality( Qt::WindowModal ); } for ( int i = 0; i < mNumRows; ++i ) { currentXValue = mInterpolationExtent.xMinimum() + mCellSizeX / 2.0; //calculate value in the center of the cell for ( int j = 0; j < mNumColumns; ++j ) { if ( mInterpolator->interpolatePoint( currentXValue, currentYValue, interpolatedValue ) == 0 ) { outStream << interpolatedValue << " "; } else { outStream << "-9999 "; } currentXValue += mCellSizeX; } outStream << endl; currentYValue -= mCellSizeY; if ( showProgressDialog ) { if ( progressDialog->wasCanceled() ) { outputFile.remove(); return 3; } progressDialog->setValue( i ); } } delete progressDialog; return 0; }
/*========================================================================= cutFromClipboard =========================================================================*/ bool KFileBrowser::cutFromClipboard (const FileClipboard *fc) { const QStringList &names = fc->getNames(); QMessageBox msgBox; msgBox.setText(tr("Confirm move")); if (names.count() == 1) msgBox.setInformativeText (tr("Do you want to move this item?")); else { char ss[20]; sprintf (ss, "%d", names.count()); msgBox.setInformativeText ((QString)tr("Do you want to move these") + " " + ss + " " + tr ("items") + "?"); } msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Cancel); int r = msgBox.exec(); if (r != QMessageBox::Ok) return false; bool ret = FALSE; const QString &root = fc->getRoot(); int l = names.count(); int itemsDone = 0; QProgressDialog progress (tr("Moving files..."), tr("Stop"), 0, l, this); progress.setWindowModality (Qt::WindowModal); progress.setMinimumDuration (0); progress.show(); bool stop = false; QString errorMessage = ""; for (int i = 0; i < l && !progress.wasCanceled() &&!stop; i++) { QString sourceName = root + "/" + names[i]; QString targetName; if (fc->getPasteByNameOnly()) { QFileInfo info (path + "/" + names[i]); QString shortName = info.fileName(); targetName = path + "/" + shortName; } else targetName = path + "/" + names[i]; errorMessage = ""; if (sourceName == targetName) { errorMessage = tr ("Source and destination files are the same"); } else { QFileInfo info (sourceName); if (info.isDir()) { QDir dir; if (dir.rename (sourceName, targetName)) itemsDone++; else errorMessage = tr("Can't move directory"); } else { QFile file; if (file.rename (sourceName, targetName)) itemsDone++; else errorMessage = tr("Can't move file"); } } if (errorMessage != "") { if (i < l - 1) { QMessageBox msgBox; msgBox.setText(tr("Error copying file")); msgBox.setInformativeText (errorMessage + ". " + tr("Do you want to coninue with the next item?")); msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Cancel); int ret = msgBox.exec(); if (ret != QMessageBox::Ok) stop = true; } else error (errorMessage); } progress.setValue (i); } if (progress.wasCanceled()) message ("canceled"); progress.setValue (l); ret = true; if (stop) ret = false; if (progress.wasCanceled()) ret = false; if (errorMessage != "") ret = false; emit dirContentsChanged(); QString sm = tr("Moved"); char ss[20]; sprintf (ss, "%d", itemsDone); sm += ss; sm += " " + (itemsDone == 1 ? tr("items") : tr("items")); emit statusUpdate (sm); return ret; }
void Main_GUI::run() { statusBar()->clearMessage(); QString input_name = QDir::fromNativeSeparators(input_line->text()); QString output_name = QDir::fromNativeSeparators(output_line->text()); if (!check_filenames(input_name, output_name)) return; // we need C file descriptors for communication with TTF_autohint FILE* input; FILE* output; again: if (!open_files(input_name, &input, output_name, &output)) return; QProgressDialog dialog; dialog.setCancelButtonText(tr("Cancel")); dialog.setMinimumDuration(1000); dialog.setWindowModality(Qt::WindowModal); const unsigned char* error_string; TA_Info_Func info_func = info; GUI_Progress_Data gui_progress_data = {-1, true, &dialog}; Info_Data info_data; info_data.data = NULL; // must be deallocated after use info_data.data_wide = NULL; // must be deallocated after use info_data.data_len = 0; info_data.data_wide_len = 0; info_data.hinting_range_min = min_box->value(); info_data.hinting_range_max = max_box->value(); info_data.hinting_limit = no_limit_box->isChecked() ? 0 : limit_box->value(); info_data.gray_strong_stem_width = gray_box->isChecked(); info_data.gdi_cleartype_strong_stem_width = gdi_box->isChecked(); info_data.dw_cleartype_strong_stem_width = dw_box->isChecked(); info_data.increase_x_height = no_increase_box->isChecked() ? 0 : increase_box->value(); info_data.x_height_snapping_exceptions = x_height_snapping_exceptions; info_data.windows_compatibility = wincomp_box->isChecked(); info_data.pre_hinting = pre_box->isChecked(); info_data.hint_with_components = hint_box->isChecked(); info_data.latin_fallback = fallback_box->currentIndex(); info_data.symbol = symbol_box->isChecked(); if (info_box->isChecked()) { int ret = build_version_string(&info_data); if (ret == 1) QMessageBox::information( this, "TTFautohint", tr("Can't allocate memory for <b>TTFautohint</b> options string" " in <i>name</i> table."), QMessageBox::Ok, QMessageBox::Ok); else if (ret == 2) QMessageBox::information( this, "TTFautohint", tr("<b>TTFautohint</b> options string" " in <i>name</i> table too long."), QMessageBox::Ok, QMessageBox::Ok); } else info_func = NULL; QByteArray snapping_string = snapping_line->text().toLocal8Bit(); TA_Error error = TTF_autohint("in-file, out-file," "hinting-range-min, hinting-range-max," "hinting-limit," "gray-strong-stem-width," "gdi-cleartype-strong-stem-width," "dw-cleartype-strong-stem-width," "error-string," "progress-callback, progress-callback-data," "info-callback, info-callback-data," "ignore-restrictions," "windows-compatibility," "pre-hinting," "hint-with-components," "increase-x-height," "x-height-snapping-exceptions," "fallback-script, symbol", input, output, info_data.hinting_range_min, info_data.hinting_range_max, info_data.hinting_limit, info_data.gray_strong_stem_width, info_data.gdi_cleartype_strong_stem_width, info_data.dw_cleartype_strong_stem_width, &error_string, gui_progress, &gui_progress_data, info_func, &info_data, ignore_restrictions, info_data.windows_compatibility, info_data.pre_hinting, info_data.hint_with_components, info_data.increase_x_height, snapping_string.constData(), info_data.latin_fallback, info_data.symbol); if (info_box->isChecked()) { free(info_data.data); free(info_data.data_wide); } fclose(input); fclose(output); if (error) { if (handle_error(error, error_string, output_name)) goto again; } else statusBar()->showMessage(tr("Auto-hinting finished.")); }
int QgsGml::getFeatures( const QString& uri, QGis::WkbType* wkbType, QgsRectangle* extent, const QString& userName, const QString& password ) { mUri = uri; mWkbType = wkbType; XML_Parser p = XML_ParserCreateNS( NULL, NS_SEPARATOR ); XML_SetUserData( p, this ); XML_SetElementHandler( p, QgsGml::start, QgsGml::end ); XML_SetCharacterDataHandler( p, QgsGml::chars ); //start with empty extent mExtent.setMinimal(); QNetworkRequest request( mUri ); if ( !userName.isNull() || !password.isNull() ) { request.setRawHeader( "Authorization", "Basic " + QString( "%1:%2" ).arg( userName ).arg( password ).toAscii().toBase64() ); } QNetworkReply* reply = QgsNetworkAccessManager::instance()->get( request ); connect( reply, SIGNAL( finished() ), this, SLOT( setFinished() ) ); connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( handleProgressEvent( qint64, qint64 ) ) ); //find out if there is a QGIS main window. If yes, display a progress dialog QProgressDialog* progressDialog = 0; QWidget* mainWindow = 0; QWidgetList topLevelWidgets = qApp->topLevelWidgets(); for ( QWidgetList::iterator it = topLevelWidgets.begin(); it != topLevelWidgets.end(); ++it ) { if (( *it )->objectName() == "QgisApp" ) { mainWindow = *it; break; } } if ( mainWindow ) { progressDialog = new QProgressDialog( tr( "Loading GML data\n%1" ).arg( mTypeName ), tr( "Abort" ), 0, 0, mainWindow ); progressDialog->setWindowModality( Qt::ApplicationModal ); connect( this, SIGNAL( dataReadProgress( int ) ), progressDialog, SLOT( setValue( int ) ) ); connect( this, SIGNAL( totalStepsUpdate( int ) ), progressDialog, SLOT( setMaximum( int ) ) ); connect( progressDialog, SIGNAL( canceled() ), this, SLOT( setFinished() ) ); progressDialog->show(); } int atEnd = 0; while ( !atEnd ) { if ( mFinished ) { atEnd = 1; } QByteArray readData = reply->readAll(); if ( readData.size() > 0 ) { if ( XML_Parse( p, readData.constData(), readData.size(), atEnd ) == 0 ) { XML_Error errorCode = XML_GetErrorCode( p ); QString errorString = tr( "Error: %1 on line %2, column %3" ) .arg( XML_ErrorString( errorCode ) ) .arg( XML_GetCurrentLineNumber( p ) ) .arg( XML_GetCurrentColumnNumber( p ) ); QgsMessageLog::logMessage( errorString, tr( "WFS" ) ); } } QCoreApplication::processEvents(); } QNetworkReply::NetworkError replyError = reply->error(); QString replyErrorString = reply->errorString(); delete reply; delete progressDialog; if ( replyError ) { QgsMessageLog::logMessage( tr( "GML Getfeature network request failed with error: %1" ).arg( replyErrorString ), tr( "Network" ), QgsMessageLog::CRITICAL ); return 1; } if ( *mWkbType != QGis::WKBNoGeometry ) { if ( mExtent.isEmpty() ) { //reading of bbox from the server failed, so we calculate it less efficiently by evaluating the features calculateExtentFromFeatures(); } } XML_ParserFree( p ); if ( extent ) *extent = mExtent; return 0; }
int QgsGml::getFeatures( const QString &uri, QgsWkbTypes::Type *wkbType, QgsRectangle *extent, const QString &userName, const QString &password, const QString &authcfg ) { //start with empty extent mExtent.setMinimal(); QNetworkRequest request( uri ); if ( !authcfg.isEmpty() ) { if ( !QgsApplication::authManager()->updateNetworkRequest( request, authcfg ) ) { QgsMessageLog::logMessage( tr( "GML Getfeature network request update failed for authcfg %1" ).arg( authcfg ), tr( "Network" ), Qgis::Critical ); return 1; } } else if ( !userName.isNull() || !password.isNull() ) { request.setRawHeader( "Authorization", "Basic " + QStringLiteral( "%1:%2" ).arg( userName, password ).toLatin1().toBase64() ); } QNetworkReply *reply = QgsNetworkAccessManager::instance()->get( request ); if ( !authcfg.isEmpty() ) { if ( !QgsApplication::authManager()->updateNetworkReply( reply, authcfg ) ) { reply->deleteLater(); QgsMessageLog::logMessage( tr( "GML Getfeature network reply update failed for authcfg %1" ).arg( authcfg ), tr( "Network" ), Qgis::Critical ); return 1; } } connect( reply, &QNetworkReply::finished, this, &QgsGml::setFinished ); connect( reply, &QNetworkReply::downloadProgress, this, &QgsGml::handleProgressEvent ); //find out if there is a QGIS main window. If yes, display a progress dialog QProgressDialog *progressDialog = nullptr; QWidget *mainWindow = nullptr; QWidgetList topLevelWidgets = qApp->topLevelWidgets(); for ( QWidgetList::const_iterator it = topLevelWidgets.constBegin(); it != topLevelWidgets.constEnd(); ++it ) { if ( ( *it )->objectName() == QLatin1String( "QgisApp" ) ) { mainWindow = *it; break; } } if ( mainWindow ) { progressDialog = new QProgressDialog( tr( "Loading GML data\n%1" ).arg( mTypeName ), tr( "Abort" ), 0, 0, mainWindow ); progressDialog->setWindowModality( Qt::ApplicationModal ); connect( this, &QgsGml::dataReadProgress, progressDialog, &QProgressDialog::setValue ); connect( this, &QgsGml::totalStepsUpdate, progressDialog, &QProgressDialog::setMaximum ); connect( progressDialog, &QProgressDialog::canceled, this, &QgsGml::setFinished ); progressDialog->show(); } int atEnd = 0; while ( !atEnd ) { if ( mFinished ) { atEnd = 1; } QByteArray readData = reply->readAll(); if ( !readData.isEmpty() ) { QString errorMsg; if ( !mParser.processData( readData, atEnd, errorMsg ) ) QgsMessageLog::logMessage( errorMsg, QObject::tr( "WFS" ) ); } QCoreApplication::processEvents(); } fillMapsFromParser(); QNetworkReply::NetworkError replyError = reply->error(); QString replyErrorString = reply->errorString(); delete reply; delete progressDialog; if ( replyError ) { QgsMessageLog::logMessage( tr( "GML Getfeature network request failed with error: %1" ).arg( replyErrorString ), tr( "Network" ), Qgis::Critical ); return 1; } *wkbType = mParser.wkbType(); if ( *wkbType != QgsWkbTypes::Unknown ) { if ( mExtent.isEmpty() ) { //reading of bbox from the server failed, so we calculate it less efficiently by evaluating the features calculateExtentFromFeatures(); } } if ( extent ) *extent = mExtent; return 0; }
bool QgsSLConnectionItem::handleDrop( const QMimeData * data, Qt::DropAction ) { if ( !QgsMimeDataUtils::isUriList( data ) ) return false; // TODO: probably should show a GUI with settings etc QgsDataSourceURI destUri; destUri.setDatabase( mDbPath ); qApp->setOverrideCursor( Qt::WaitCursor ); QProgressDialog *progress = new QProgressDialog( tr( "Copying features..." ), tr( "Abort" ), 0, 0, nullptr ); progress->setWindowTitle( tr( "Import layer" ) ); progress->setWindowModality( Qt::WindowModal ); progress->show(); QStringList importResults; bool hasError = false; bool cancelled = false; QgsMimeDataUtils::UriList lst = QgsMimeDataUtils::decodeUriList( data ); Q_FOREACH ( const QgsMimeDataUtils::Uri& u, lst ) { if ( u.layerType != "vector" ) { importResults.append( tr( "%1: Not a vector layer!" ).arg( u.name ) ); hasError = true; // only vectors can be imported continue; } // open the source layer QgsVectorLayer* srcLayer = new QgsVectorLayer( u.uri, u.name, u.providerKey ); if ( srcLayer->isValid() ) { destUri.setDataSource( QString(), u.name, srcLayer->geometryType() != Qgis::NoGeometry ? "geom" : QString() ); QgsDebugMsg( "URI " + destUri.uri() ); QgsVectorLayerImport::ImportError err; QString importError; err = QgsVectorLayerImport::importLayer( srcLayer, destUri.uri(), "spatialite", srcLayer->crs(), false, &importError, false, nullptr, progress ); if ( err == QgsVectorLayerImport::NoError ) importResults.append( tr( "%1: OK!" ).arg( u.name ) ); else if ( err == QgsVectorLayerImport::ErrUserCancelled ) cancelled = true; else { importResults.append( QString( "%1: %2" ).arg( u.name, importError ) ); hasError = true; } } else { importResults.append( tr( "%1: OK!" ).arg( u.name ) ); hasError = true; } delete srcLayer; } delete progress; qApp->restoreOverrideCursor(); if ( cancelled ) { QMessageBox::information( nullptr, tr( "Import to SpatiaLite database" ), tr( "Import cancelled." ) ); refresh(); } else if ( hasError ) { QgsMessageOutput *output = QgsMessageOutput::createMessageOutput(); output->setTitle( tr( "Import to SpatiaLite database" ) ); output->setMessage( tr( "Failed to import some layers!\n\n" ) + importResults.join( "\n" ), QgsMessageOutput::MessageText ); output->showMessage(); } else { QMessageBox::information( nullptr, tr( "Import to SpatiaLite database" ), tr( "Import was successful." ) ); refresh(); } return true; }
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); }
void FontSelectFrame::setFontsDirectory(QString dir_name) { if (m_config) m_config->setPath(dir_name); m_database.clear(); ui->lineEditFontsDir->setText(dir_name); FT_Library library = 0; int error = FT_Init_FreeType(&library); if (error) { qDebug() << "FT_Open_Library error " << error; return; } QDir dir(dir_name); QStringList files = dir.entryList( QStringList() << "*.ttf" << "*.pcf" << "*.ttc" << "*.pcf.gz" << "*.otf", QDir::Files | QDir::Readable ); QProgressDialog* progress = 0; if (!files.isEmpty()) { progress = new QProgressDialog( tr("Scanning directory.."), tr("Cancel"), 0,files.size(),this); progress->setCancelButton(0); progress->setWindowModality(Qt::WindowModal); //progress->show(); } int progress_val = 0; foreach (QString file_name, files) { //qDebug() << "found font file : " << file_name; QFile file(dir.filePath(file_name)); if (file.open(QFile::ReadOnly)) { QByteArray bytes = file.readAll(); const FT_Byte* data = reinterpret_cast<const FT_Byte* >(bytes.data()); FT_Face face; int error = FT_New_Memory_Face(library, data,bytes.size(),-1,&face); if (error==0) { int faces_num = face->num_faces; FT_Done_Face(face); for (int face_n = 0;face_n<faces_num;face_n++) { error = FT_New_Memory_Face(library, data,bytes.size(),face_n,&face); /// skip font if load error if (error!=0) continue; QString family = face->family_name; //qDebug() << "face " << family << " " // << face->style_name; /// skip font if not have family if (family.isEmpty()) continue; bool fixedsizes = (FT_FACE_FLAG_SCALABLE & face->face_flags ) == 0; m_database[face->family_name].push_back( FontDef(face->style_name, file_name, face_n, fixedsizes)); if (fixedsizes) { for (int i=0;i<face->num_fixed_sizes;i++) { m_database[family].back().fixedsizes.push_back( QPair<int,int>( face->available_sizes[i].width, face->available_sizes[i].height)); } qDebug() << " fixed sizes " << m_database[family].back().fixedsizes; } FT_Done_Face(face); } } } progress_val++; progress->setValue(progress_val); }