/*! This function is used to parse the given QString for variables. If found the user will be prompted for a replacement value. It returns the string text with all replacements made */ QString SnippetWidget::parseText(QString text, QString del) { QString str = text; QString strName = ""; QString strNew = ""; QString strMsg=""; int iFound = -1; int iEnd = -1; QMap<QString, QString> mapVar; int iInMeth = _SnippetConfig.getInputMethod(); QRect rSingle = _SnippetConfig.getSingleRect(); QRect rMulti = _SnippetConfig.getMultiRect(); do { iFound = text.find(QRegExp("\\"+del+"[A-Za-z-_0-9\\s]*\\"+del), iEnd+1); //find the next variable by this QRegExp if (iFound >= 0) { iEnd = text.find(del, iFound+1)+1; strName = text.mid(iFound, iEnd-iFound); if ( strName != del+del ) { //if not doubel-delimiter if (iInMeth == 0) { //if input-method "single" is selected if ( mapVar[strName].length() <= 0 ) { // and not already in map strMsg=i18n("Please enter the value for <b>%1</b>:").arg(strName); strNew = showSingleVarDialog( strName, &_mapSaved, rSingle ); if (strNew=="") return ""; //user clicked Cancle } else { continue; //we have already handled this variable } } else { strNew = ""; //for inputmode "multi" just reset new valaue } } else { strNew = del; //if double-delimiter -> replace by single character } if (iInMeth == 0) { //if input-method "single" is selected str.replace(strName, strNew); } mapVar[strName] = strNew; } } while (iFound != -1); if (iInMeth == 1) { //check config, if input-method "multi" is selected int w, bh, oh; w = rMulti.width(); bh = rMulti.height(); oh = rMulti.top(); if (showMultiVarDialog( &mapVar, &_mapSaved, w, bh, oh )) { //generate and show the dialog QMap<QString, QString>::Iterator it; for ( it = mapVar.begin(); it != mapVar.end(); ++it ) { //walk through the map and do the replacement str.replace(it.key(), it.data()); } } else { return ""; } rMulti.setWidth(w); //this is a hack to save the dialog's dimensions in only one QRect rMulti.setHeight(bh); rMulti.setTop(oh); rMulti.setLeft(0); _SnippetConfig.setMultiRect(rMulti); } _SnippetConfig.setSingleRect(rSingle); return str; }
// write XPM image data static bool write_xpm_image(const QImage &sourceImage, QIODevice *device, const QString &fileName) { if (!device->isWritable()) return false; QImage image; if (sourceImage.depth() != 32) image = sourceImage.convertToFormat(QImage::Format_RGB32); else image = sourceImage; QMap<QRgb, int> colorMap; int w = image.width(), h = image.height(), ncolors = 0; int x, y; // build color table for(y=0; y<h; y++) { QRgb * yp = (QRgb *)image.scanLine(y); for(x=0; x<w; x++) { QRgb color = *(yp + x); if (!colorMap.contains(color)) colorMap.insert(color, ncolors++); } } // number of 64-bit characters per pixel needed to encode all colors int cpp = 1; for (int k = 64; ncolors > k; k *= 64) { ++cpp; // limit to 4 characters per pixel // 64^4 colors is enough for a 4096x4096 image if (cpp > 4) break; } QString line; // write header QTextStream s(device); s << "/* XPM */" << endl << "static char *" << fbname(fileName) << "[]={" << endl << '\"' << w << ' ' << h << ' ' << ncolors << ' ' << cpp << '\"'; // write palette QMap<QRgb, int>::Iterator c = colorMap.begin(); while (c != colorMap.end()) { QRgb color = c.key(); if (image.format() != QImage::Format_RGB32 && !qAlpha(color)) line.sprintf("\"%s c None\"", xpm_color_name(cpp, *c)); else line.sprintf("\"%s c #%02x%02x%02x\"", xpm_color_name(cpp, *c), qRed(color), qGreen(color), qBlue(color)); ++c; s << ',' << endl << line; } // write pixels, limit to 4 characters per pixel line.truncate(cpp*w); for(y=0; y<h; y++) { QRgb * yp = (QRgb *) image.scanLine(y); int cc = 0; for(x=0; x<w; x++) { int color = (int)(*(yp + x)); QByteArray chars(xpm_color_name(cpp, colorMap[color])); line[cc++] = QLatin1Char(chars[0]); if (cpp > 1) { line[cc++] = QLatin1Char(chars[1]); if (cpp > 2) { line[cc++] = QLatin1Char(chars[2]); if (cpp > 3) { line[cc++] = QLatin1Char(chars[3]); } } } } s << ',' << endl << '\"' << line << '\"'; } s << "};" << endl; return (s.status() == QTextStream::Ok); }
DTC::ProgramList* Dvr::GetRecordedList( bool bDescending, int nStartIndex, int nCount, const QString &sTitleRegEx, const QString &sRecGroup, const QString &sStorageGroup ) { QMap< QString, ProgramInfo* > recMap; if (gCoreContext->GetScheduler()) recMap = gCoreContext->GetScheduler()->GetRecording(); QMap< QString, uint32_t > inUseMap = ProgramInfo::QueryInUseMap(); QMap< QString, bool > isJobRunning= ProgramInfo::QueryJobsRunning(JOB_COMMFLAG); ProgramList progList; int desc = 1; if (bDescending) desc = -1; LoadFromRecorded( progList, false, inUseMap, isJobRunning, recMap, desc ); QMap< QString, ProgramInfo* >::iterator mit = recMap.begin(); for (; mit != recMap.end(); mit = recMap.erase(mit)) delete *mit; // ---------------------------------------------------------------------- // Build Response // ---------------------------------------------------------------------- DTC::ProgramList *pPrograms = new DTC::ProgramList(); int nAvailable = 0; int nMax = (nCount > 0) ? nCount : progList.size(); nAvailable = 0; nCount = 0; QRegExp rTitleRegEx = QRegExp(sTitleRegEx, Qt::CaseInsensitive); for( unsigned int n = 0; n < progList.size(); n++) { ProgramInfo *pInfo = progList[ n ]; if (pInfo->IsDeletePending() || (!sTitleRegEx.isEmpty() && !pInfo->GetTitle().contains(rTitleRegEx)) || (!sRecGroup.isEmpty() && sRecGroup != pInfo->GetRecordingGroup()) || (!sStorageGroup.isEmpty() && sStorageGroup != pInfo->GetStorageGroup())) continue; if ((nAvailable < nStartIndex) || (nCount >= nMax)) { ++nAvailable; continue; } ++nAvailable; ++nCount; DTC::Program *pProgram = pPrograms->AddNewProgram(); FillProgramInfo( pProgram, pInfo, true ); } // ---------------------------------------------------------------------- pPrograms->setStartIndex ( nStartIndex ); pPrograms->setCount ( nCount ); pPrograms->setTotalAvailable( nAvailable ); pPrograms->setAsOf ( MythDate::current() ); pPrograms->setVersion ( MYTH_BINARY_VERSION ); pPrograms->setProtoVer ( MYTH_PROTO_VERSION ); return pPrograms; }
void FillIn::updateMetrics() { QSharedPointer<Food> selectedFood = getSelectedFood(); if (!selectedFood) { ui.btnFillIn->setEnabled(false); ui.txtAmount->setText(""); ui.txtAverageError->setText(""); ui.txtLargestError->setText(""); ui.txtLargestErrorField->setText(""); ui.txtLargestErrorSelectedVal->setText(""); ui.txtLargestErrorYourVal->setText(""); ui.txtNumFields->setText(""); ui.txtStdDev->setText(""); fillinNutrients.clear(); } else { ui.btnFillIn->setEnabled(true); // TODO: Break this up into multiple methods // Step 1. Compute the amount of the selected food needed to give the same // number of calories as the original food QSharedPointer<const Nutrient> calories = Nutrient::getNutrientByName(Nutrient::CALORIES_NAME); FoodAmount selectedBaseAmount = selectedFood->getBaseAmount(); double caloriesInOriginal = originalNutrients[calories->getId()].getAmount(); double caloriesInSelectedBaseAmount = selectedBaseAmount.getScaledNutrients()[calories->getId()].getAmount(); qDebug() << "Calories in original: " << caloriesInOriginal; qDebug() << "Calories in selected base amount: " << selectedBaseAmount.getScaledNutrients()[calories->getId()].getAmount(); FoodAmount selectedAmount = selectedBaseAmount * (caloriesInOriginal / caloriesInSelectedBaseAmount); ui.txtAmount->setText(QString::number(selectedAmount.getAmount(), 'f', 2) + " " + selectedAmount.getUnit()->getAbbreviation()); // Step 2. Determine which nutrients are in common, and which can be filled in QMap<QString, NutrientAmount> selectedNutrients = selectedAmount.getScaledNutrients(); QSet<QString> originalNutrientIds = originalNutrients.keys().toSet(); QSet<QString> selectedNutrientIds = selectedNutrients.keys().toSet(); QSet<QString> commonNutrientIds = originalNutrientIds; commonNutrientIds.intersect(selectedNutrientIds); QSet<QString> fillinNutrientIds = selectedNutrientIds; fillinNutrientIds.subtract(originalNutrientIds); qDebug() << "Original nutrients: " << originalNutrientIds.size(); qDebug() << "Selected nutrients: " << selectedNutrientIds.size(); qDebug() << "Common nutrients: " << commonNutrientIds.size(); qDebug() << "Fill-in nutrients: " << fillinNutrientIds.size(); ui.txtNumFields->setText(QString::number(fillinNutrientIds.size())); // Step 3. Compute the percent error for each common nutrient, and compute // the average, also making note of the largest. QMap<QString, double> pctError; double sumOfErrors = 0; QString largestErrorId; double largestError = 0; for (QSet<QString>::const_iterator i = commonNutrientIds.begin(); i != commonNutrientIds.end(); ++i) { double originalValue = originalNutrients[*i].getAmount(); if (originalValue > 0) { double selectedValue = selectedNutrients[*i].getAmount(); double error = std::fabs(originalValue - selectedValue) / originalValue; pctError[*i] = error; sumOfErrors += error; if (error > largestError) { largestErrorId = *i; largestError = error; } qDebug() << "Error for common nutrient " << *i << " (" << originalNutrients[*i].getNutrient()->getName() << ") is " << error; } } double avgError = sumOfErrors / pctError.size(); ui.txtAverageError->setText(QString::number(avgError * 100, 'f', 2) + " %"); ui.txtLargestError->setText(QString::number(largestError * 100, 'f', 2) + " %"); ui.txtLargestErrorField->setText(originalNutrients[largestErrorId].getNutrient()->getName()); ui.txtLargestErrorYourVal->setText (QString::number(originalNutrients[largestErrorId].getAmount(), 'f', 2) + " " + originalNutrients[largestErrorId].getUnit()->getAbbreviation()); ui.txtLargestErrorSelectedVal->setText (QString::number(selectedNutrients[largestErrorId].getAmount(), 'f', 2) + " " + selectedNutrients[largestErrorId].getUnit()->getAbbreviation()); // Step 4. Compute the standard deviation of the error percentages double sumOfDistancesSquared = 0; for (QMap<QString, double>::const_iterator i = pctError.begin(); i != pctError.end(); ++i) { double distance = i.value() - avgError; sumOfDistancesSquared += (distance * distance); } double stdDev = std::sqrt(sumOfDistancesSquared / pctError.size()); ui.txtStdDev->setText(QString::number(stdDev, 'f', 2)); // Step 5. Save a copy of all of the fill-in nutrient amounts fillinNutrients.clear(); for (QSet<QString>::const_iterator i = fillinNutrientIds.begin(); i != fillinNutrientIds.end(); ++i) { fillinNutrients[*i] = selectedNutrients[*i]; } } }
ImportOptionsDlg::ImportOptionsDlg(Importer* pImporter, const QMap<QString, vector<ImportDescriptor*> >& files, QWidget* pParent) : QDialog(pParent), mpImporter(pImporter), mpCurrentDataset(NULL), mpEditDescriptor(NULL), mEditDataDescriptorModified(false), mPromptForChanges(true), mAllowDeselectedFiles(true), mpDatasetTree(NULL), mpClassificationLabel(NULL), mpTabWidget(NULL), mpDataPage(NULL), mpFilePage(NULL), mpClassificationPage(NULL), mpSubsetPage(NULL), mpMetadataPage(NULL), mpWavelengthsPage(NULL), mpImporterPage(NULL), mpValidationLabel(NULL) { QSplitter* pSplitter = new QSplitter(this); // Dataset list QWidget* pDatasetWidget = new QWidget(pSplitter); QLabel* pDatasetLabel = new QLabel("Data Sets:", pDatasetWidget); mpDatasetTree = new QTreeWidget(pDatasetWidget); mpDatasetTree->setSelectionMode(QAbstractItemView::SingleSelection); mpDatasetTree->setSelectionBehavior(QAbstractItemView::SelectItems); mpDatasetTree->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); mpDatasetTree->setTextElideMode(Qt::ElideLeft); mpDatasetTree->setMinimumWidth(225); mpDatasetTree->setHeaderHidden(true); QPushButton* pImportAllButton = new QPushButton("Import All", pDatasetWidget); QPushButton* pImportNoneButton = new QPushButton("Import None", pDatasetWidget); // Classification label QWidget* pInfoWidget = new QWidget(pSplitter); QFont labelFont = font(); labelFont.setBold(true); mpClassificationLabel = new QLabel(pInfoWidget); mpClassificationLabel->setFont(labelFont); mpClassificationLabel->setAlignment(Qt::AlignCenter); // Tab widget mpTabWidget = new QTabWidget(pInfoWidget); mpDataPage = new DataDescriptorWidget(); mpFilePage = new FileDescriptorWidget(); mpClassificationPage = new ClassificationWidget(); mpSubsetPage = new SubsetWidget(); mpMetadataPage = new MetadataWidget(); mpWavelengthsPage = new WavelengthsWidget(); mpTabWidget->addTab(mpDataPage, "Data"); mpTabWidget->addTab(mpFilePage, "File"); mpTabWidget->addTab(mpClassificationPage, "Classification"); mpTabWidget->addTab(mpSubsetPage, "Subset"); mpTabWidget->addTab(mpMetadataPage, "Metadata"); // Validation label mpValidationLabel = new QLabel(this); mpValidationLabel->setWordWrap(true); QFont validationFont = mpValidationLabel->font(); validationFont.setBold(true); mpValidationLabel->setFont(validationFont); // Dialog buttons mpOkButton = new QPushButton("&OK", this); QPushButton* pCancelButton = new QPushButton("&Cancel", this); // Layout QLayout* pDataLayout = mpDataPage->layout(); if (pDataLayout != NULL) { pDataLayout->setMargin(10); } QLayout* pFileLayout = mpFilePage->layout(); if (pFileLayout != NULL) { pFileLayout->setMargin(10); } QLayout* pClassificationLayout = mpClassificationPage->layout(); if (pClassificationLayout != NULL) { pClassificationLayout->setMargin(10); } QLayout* pSubsetLayout = mpSubsetPage->layout(); if (pSubsetLayout != NULL) { pSubsetLayout->setMargin(10); } QLayout* pMetadataLayout = mpMetadataPage->layout(); if (pMetadataLayout != NULL) { pMetadataLayout->setMargin(10); } QLayout* pWavelengthsLayout = mpWavelengthsPage->layout(); if (pWavelengthsLayout != NULL) { pWavelengthsLayout->setMargin(10); } QGridLayout* pDatasetLayout = new QGridLayout(pDatasetWidget); pDatasetLayout->setMargin(0); pDatasetLayout->setSpacing(5); pDatasetLayout->addWidget(pDatasetLabel, 0, 0, 1, 2); pDatasetLayout->addWidget(mpDatasetTree, 1, 0, 1, 2); pDatasetLayout->addWidget(pImportAllButton, 2, 0, Qt::AlignRight); pDatasetLayout->addWidget(pImportNoneButton, 2, 1); pDatasetLayout->setRowStretch(1, 10); pDatasetLayout->setColumnStretch(0, 10); QVBoxLayout* pInfoLayout = new QVBoxLayout(pInfoWidget); pInfoLayout->setMargin(0); pInfoLayout->setSpacing(10); pInfoLayout->addWidget(mpClassificationLabel); pInfoLayout->addWidget(mpTabWidget, 10); QHBoxLayout* pButtonLayout = new QHBoxLayout(); pButtonLayout->setMargin(0); pButtonLayout->setSpacing(5); pButtonLayout->addWidget(mpValidationLabel, 10); pButtonLayout->addWidget(mpOkButton, 0, Qt::AlignBottom); pButtonLayout->addWidget(pCancelButton, 0, Qt::AlignBottom); QVBoxLayout* pVBox = new QVBoxLayout(this); pVBox->setMargin(10); pVBox->setSpacing(10); pVBox->addWidget(pSplitter, 10); pVBox->addLayout(pButtonLayout); // Initialization setWindowTitle("Import Options"); setModal(true); resize(700, 450); pSplitter->addWidget(pDatasetWidget); pSplitter->addWidget(pInfoWidget); // Populate the data set tree widget QTreeWidgetItem* pSelectItem = NULL; QMap<QString, vector<ImportDescriptor*> >::const_iterator fileIter; for (fileIter = files.begin(); fileIter != files.end(); ++fileIter) { // Filename item QString filename = fileIter.key(); if (filename.isEmpty() == true) { continue; } QTreeWidgetItem* pFileItem = new QTreeWidgetItem(mpDatasetTree); QFileInfo fileInfo(filename); pFileItem->setText(0, fileInfo.fileName()); pFileItem->setIcon(0, style()->standardIcon(QStyle::SP_FileIcon)); pFileItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); pFileItem->setToolTip(0, filename); pFileItem->setCheckState(0, Qt::Unchecked); // Dataset items vector<ImportDescriptor*> fileDatasets = fileIter.value(); vector<ImportDescriptor*> datasets; copy(fileDatasets.begin(), fileDatasets.end(), back_inserter(datasets)); stable_sort(datasets.begin(), datasets.end(), ElementDepthComparitor()); map<vector<string>, QTreeWidgetItem*> parentPaths; vector<ImportDescriptor*>::iterator datasetIter; for (datasetIter = datasets.begin(); datasetIter != datasets.end(); ++datasetIter) { ImportDescriptor* pImportDescriptor = *datasetIter; if (pImportDescriptor == NULL) { continue; } DataDescriptor* pDescriptor = pImportDescriptor->getDataDescriptor(); if (pDescriptor == NULL) { continue; } const string& name = pDescriptor->getName(); if (name.empty()) { continue; } QTreeWidgetItem* pItem = new QTreeWidgetItem(static_cast<QTreeWidget*>(NULL), QStringList() << QString::fromStdString(name)); if (pItem == NULL) { continue; } // Tool tip pItem->setToolTip(0, QString::fromStdString(name)); // Check state Qt::ItemFlags itemFlags = pItem->flags(); itemFlags |= Qt::ItemIsUserCheckable; pItem->setFlags(itemFlags); if (pImportDescriptor->isImported()) { pItem->setCheckState(0, Qt::Checked); if (pSelectItem == NULL) { pSelectItem = pItem; } } else { pItem->setCheckState(0, Qt::Unchecked); } // Add to the proper parent map<vector<string>, QTreeWidgetItem*>::iterator parent = parentPaths.find(pDescriptor->getParentDesignator()); if (parent != parentPaths.end()) { parent->second->addChild(pItem); } else { pFileItem->addChild(pItem); } vector<string> myDesignator = pDescriptor->getParentDesignator(); myDesignator.push_back(pDescriptor->getName()); parentPaths[myDesignator] = pItem; mDatasets[pImportDescriptor] = pItem; validateDataset(pDescriptor); enforceSelections(pItem); } } mpDatasetTree->expandAll(); // Update the tab widget for the selected data set if (pSelectItem == NULL) { // No data set is set to import by default so select the first data set in the tree widget for (int i = 0; i < mpDatasetTree->topLevelItemCount() && pSelectItem == NULL; ++i) { QTreeWidgetItem* pParentItem = mpDatasetTree->topLevelItem(i); if ((pParentItem != NULL) && (pParentItem->childCount() > 0)) { pSelectItem = pParentItem->child(0); } } } if (pSelectItem != NULL) { mpDatasetTree->setItemSelected(pSelectItem, true); updateEditDataset(); } // Connections VERIFYNR(connect(mpDatasetTree, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(datasetItemChanged(QTreeWidgetItem*)))); VERIFYNR(connect(mpDatasetTree, SIGNAL(itemSelectionChanged()), this, SLOT(updateEditDataset()))); VERIFYNR(connect(pImportAllButton, SIGNAL(clicked()), this, SLOT(selectAllDatasets()))); VERIFYNR(connect(pImportNoneButton, SIGNAL(clicked()), this, SLOT(deselectAllDatasets()))); VERIFYNR(connect(mpOkButton, SIGNAL(clicked()), this, SLOT(accept()))); VERIFYNR(connect(pCancelButton, SIGNAL(clicked()), this, SLOT(reject()))); updateConnections(true); }
void ConfCertDialog::loadAll() { for(QMap<RsPeerId, ConfCertDialog*>::iterator it = instances_ssl.begin(); it != instances_ssl.end(); ++it) it.value()->load(); for(QMap<RsPgpId , ConfCertDialog*>::iterator it = instances_pgp.begin(); it != instances_pgp.end(); ++it) it.value()->load(); }
void QgsOfflineEditing::synchronize() { // open logging db sqlite3* db = openLoggingDb(); if ( db == NULL ) { return; } emit progressStarted(); // restore and sync remote layers QList<QgsMapLayer*> offlineLayers; QMap<QString, QgsMapLayer*> mapLayers = QgsMapLayerRegistry::instance()->mapLayers(); for ( QMap<QString, QgsMapLayer*>::iterator layer_it = mapLayers.begin() ; layer_it != mapLayers.end(); ++layer_it ) { QgsMapLayer* layer = layer_it.value(); if ( layer->customProperty( CUSTOM_PROPERTY_IS_OFFLINE_EDITABLE, false ).toBool() ) { offlineLayers << layer; } } for ( int l = 0; l < offlineLayers.count(); l++ ) { QgsMapLayer* layer = offlineLayers[l]; emit layerProgressUpdated( l + 1, offlineLayers.count() ); QString remoteSource = layer->customProperty( CUSTOM_PROPERTY_REMOTE_SOURCE, "" ).toString(); QString remoteProvider = layer->customProperty( CUSTOM_PROPERTY_REMOTE_PROVIDER, "" ).toString(); QString remoteName = layer->name(); remoteName.remove( QRegExp( " \\(offline\\)$" ) ); QgsVectorLayer* remoteLayer = new QgsVectorLayer( remoteSource, remoteName, remoteProvider ); if ( remoteLayer->isValid() ) { // TODO: only add remote layer if there are log entries? QgsVectorLayer* offlineLayer = qobject_cast<QgsVectorLayer*>( layer ); // copy style copySymbology( offlineLayer, remoteLayer ); // register this layer with the central layers registry QgsMapLayerRegistry::instance()->addMapLayers( QList<QgsMapLayer *>() << remoteLayer, true ); // apply layer edit log QString qgisLayerId = layer->id(); QString sql = QString( "SELECT \"id\" FROM 'log_layer_ids' WHERE \"qgis_id\" = '%1'" ).arg( qgisLayerId ); int layerId = sqlQueryInt( db, sql, -1 ); if ( layerId != -1 ) { remoteLayer->startEditing(); // TODO: only get commitNos of this layer? int commitNo = getCommitNo( db ); for ( int i = 0; i < commitNo; i++ ) { // apply commits chronologically applyAttributesAdded( remoteLayer, db, layerId, i ); applyAttributeValueChanges( offlineLayer, remoteLayer, db, layerId, i ); applyGeometryChanges( remoteLayer, db, layerId, i ); } applyFeaturesAdded( offlineLayer, remoteLayer, db, layerId ); applyFeaturesRemoved( remoteLayer, db, layerId ); if ( remoteLayer->commitChanges() ) { // update fid lookup updateFidLookup( remoteLayer, db, layerId ); // clear edit log for this layer sql = QString( "DELETE FROM 'log_added_attrs' WHERE \"layer_id\" = %1" ).arg( layerId ); sqlExec( db, sql ); sql = QString( "DELETE FROM 'log_added_features' WHERE \"layer_id\" = %1" ).arg( layerId ); sqlExec( db, sql ); sql = QString( "DELETE FROM 'log_removed_features' WHERE \"layer_id\" = %1" ).arg( layerId ); sqlExec( db, sql ); sql = QString( "DELETE FROM 'log_feature_updates' WHERE \"layer_id\" = %1" ).arg( layerId ); sqlExec( db, sql ); sql = QString( "DELETE FROM 'log_geometry_updates' WHERE \"layer_id\" = %1" ).arg( layerId ); sqlExec( db, sql ); // reset commitNo QString sql = QString( "UPDATE 'log_indices' SET 'last_index' = 0 WHERE \"name\" = 'commit_no'" ); sqlExec( db, sql ); } else { showWarning( remoteLayer->commitErrors().join( "\n" ) ); } } // remove offline layer QgsMapLayerRegistry::instance()->removeMapLayers( ( QStringList() << qgisLayerId ) ); // disable offline project QString projectTitle = QgsProject::instance()->title(); projectTitle.remove( QRegExp( " \\(offline\\)$" ) ); QgsProject::instance()->title( projectTitle ); QgsProject::instance()->removeEntry( PROJECT_ENTRY_SCOPE_OFFLINE, PROJECT_ENTRY_KEY_OFFLINE_DB_PATH ); remoteLayer->reload(); //update with other changes } } emit progressStopped(); sqlite3_close( db ); }
QWidget *QgsAttributeEditor::createAttributeEditor( QWidget *parent, QWidget *editor, QgsVectorLayer *vl, int idx, const QVariant &value ) { if ( !vl ) return 0; QWidget *myWidget = 0; QgsVectorLayer::EditType editType = vl->editType( idx ); const QgsField &field = vl->pendingFields()[idx]; QVariant::Type myFieldType = field.type(); switch ( editType ) { case QgsVectorLayer::UniqueValues: { QList<QVariant> values; vl->dataProvider()->uniqueValues( idx, values ); QComboBox *cb = comboBox( editor, parent ); if ( cb ) { cb->setEditable( false ); for ( QList<QVariant>::iterator it = values.begin(); it != values.end(); it++ ) cb->addItem( it->toString(), it->toString() ); myWidget = cb; } } break; case QgsVectorLayer::Enumeration: { QStringList enumValues; vl->dataProvider()->enumValues( idx, enumValues ); QComboBox *cb = comboBox( editor, parent ); if ( cb ) { QStringList::const_iterator s_it = enumValues.constBegin(); for ( ; s_it != enumValues.constEnd(); ++s_it ) { cb->addItem( *s_it, *s_it ); } myWidget = cb; } } break; case QgsVectorLayer::ValueMap: { const QMap<QString, QVariant> &map = vl->valueMap( idx ); QComboBox *cb = comboBox( editor, parent ); if ( cb ) { for ( QMap<QString, QVariant>::const_iterator it = map.begin(); it != map.end(); it++ ) { cb->addItem( it.key(), it.value() ); } myWidget = cb; } } break; case QgsVectorLayer::ValueRelation: { QSettings settings; QString nullValue = settings.value( "qgis/nullValue", "NULL" ).toString(); const QgsVectorLayer::ValueRelationData &data = vl->valueRelation( idx ); QgsVectorLayer *layer = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( data.mLayer ) ); QMap< QString, QString > map; int fi = -1; if ( layer ) { int ki = layer->fieldNameIndex( data.mOrderByValue ? data.mValue : data.mKey ); int vi = layer->fieldNameIndex( data.mOrderByValue ? data.mKey : data.mValue ); if ( !data.mFilterAttributeColumn.isNull() ) fi = layer->fieldNameIndex( data.mFilterAttributeColumn ); if ( data.mAllowNull ) map.insert( nullValue, tr( "(no selection)" ) ); if ( ki >= 0 && vi >= 0 ) { QgsAttributeList attributes; attributes << ki; attributes << vi; if ( fi >= 0 ) attributes << fi; layer->select( attributes, QgsRectangle(), false ); QgsFeature f; while ( layer->nextFeature( f ) ) { if ( fi >= 0 && f.attributeMap()[ fi ].toString() != data.mFilterAttributeValue ) continue; map.insert( f.attributeMap()[ ki ].toString(), f.attributeMap()[ vi ].toString() ); } } } if ( !data.mAllowMulti ) { QComboBox *cb = comboBox( editor, parent ); if ( cb ) { for ( QMap< QString, QString >::const_iterator it = map.begin(); it != map.end(); it++ ) { if ( data.mOrderByValue ) cb->addItem( it.key(), it.value() ); else cb->addItem( it.value(), it.key() ); } myWidget = cb; } } else { QListWidget *lw = listWidget( editor, parent ); if ( lw ) { QStringList checkList = value.toString().remove( QChar( '{' ) ).remove( QChar( '}' ) ).split( "," ); for ( QMap< QString, QString >::const_iterator it = map.begin(); it != map.end(); it++ ) { QListWidgetItem *item; if ( data.mOrderByValue ) { item = new QListWidgetItem( it.key() ); item->setData( Qt::UserRole, it.value() ); item->setCheckState( checkList.contains( it.value() ) ? Qt::Checked : Qt::Unchecked ); } else { item = new QListWidgetItem( it.value() ); item->setData( Qt::UserRole, it.key() ); item->setCheckState( checkList.contains( it.key() ) ? Qt::Checked : Qt::Unchecked ); } lw->addItem( item ); } myWidget = lw; } } } break; case QgsVectorLayer::Classification: { QMap<QString, QString> classes; const QgsUniqueValueRenderer *uvr = dynamic_cast<const QgsUniqueValueRenderer *>( vl->renderer() ); if ( uvr ) { const QList<QgsSymbol *> symbols = uvr->symbols(); for ( int i = 0; i < symbols.size(); i++ ) { QString label = symbols[i]->label(); QString name = symbols[i]->lowerValue(); if ( label == "" ) label = name; classes.insert( name, label ); } } const QgsCategorizedSymbolRendererV2 *csr = dynamic_cast<const QgsCategorizedSymbolRendererV2 *>( vl->rendererV2() ); if ( csr ) { const QgsCategoryList &categories = (( QgsCategorizedSymbolRendererV2 * )csr )->categories(); // FIXME: QgsCategorizedSymbolRendererV2::categories() should be const for ( int i = 0; i < categories.size(); i++ ) { QString label = categories[i].label(); QString value = categories[i].value().toString(); if ( label.isEmpty() ) label = value; classes.insert( value, label ); } } QComboBox *cb = comboBox( editor, parent ); if ( cb ) { for ( QMap<QString, QString>::const_iterator it = classes.begin(); it != classes.end(); it++ ) { cb->addItem( it.value(), it.key() ); } myWidget = cb; } } break; case QgsVectorLayer::DialRange: case QgsVectorLayer::SliderRange: case QgsVectorLayer::EditRange: { if ( myFieldType == QVariant::Int ) { int min = vl->range( idx ).mMin.toInt(); int max = vl->range( idx ).mMax.toInt(); int step = vl->range( idx ).mStep.toInt(); if ( editType == QgsVectorLayer::EditRange ) { QSpinBox *sb = 0; if ( editor ) sb = qobject_cast<QSpinBox *>( editor ); else sb = new QSpinBox( parent ); if ( sb ) { sb->setRange( min, max ); sb->setSingleStep( step ); myWidget = sb; } } else { QAbstractSlider *sl = 0; if ( editor ) { sl = qobject_cast<QAbstractSlider*>( editor ); } else if ( editType == QgsVectorLayer::DialRange ) { sl = new QDial( parent ); } else { sl = new QSlider( Qt::Horizontal, parent ); } if ( sl ) { sl->setRange( min, max ); sl->setSingleStep( step ); myWidget = sl; } } break; } else if ( myFieldType == QVariant::Double ) { QDoubleSpinBox *dsb = 0; if ( editor ) dsb = qobject_cast<QDoubleSpinBox*>( editor ); else dsb = new QDoubleSpinBox( parent ); if ( dsb ) { double min = vl->range( idx ).mMin.toDouble(); double max = vl->range( idx ).mMax.toDouble(); double step = vl->range( idx ).mStep.toDouble(); dsb->setRange( min, max ); dsb->setSingleStep( step ); myWidget = dsb; } break; } } case QgsVectorLayer::CheckBox: { QCheckBox *cb = 0; if ( editor ) cb = qobject_cast<QCheckBox*>( editor ); else cb = new QCheckBox( parent ); if ( cb ) { myWidget = cb; break; } } // fall-through case QgsVectorLayer::LineEdit: case QgsVectorLayer::TextEdit: case QgsVectorLayer::UuidGenerator: case QgsVectorLayer::UniqueValuesEditable: case QgsVectorLayer::Immutable: { QLineEdit *le = 0; QTextEdit *te = 0; QPlainTextEdit *pte = 0; if ( editor ) { le = qobject_cast<QLineEdit *>( editor ); te = qobject_cast<QTextEdit *>( editor ); pte = qobject_cast<QPlainTextEdit *>( editor ); } else if ( editType == QgsVectorLayer::TextEdit ) { pte = new QPlainTextEdit( parent ); } else { le = new QLineEdit( parent ); } if ( le ) { if ( editType == QgsVectorLayer::UniqueValuesEditable ) { QList<QVariant> values; vl->dataProvider()->uniqueValues( idx, values ); QStringList svalues; for ( QList<QVariant>::const_iterator it = values.begin(); it != values.end(); it++ ) svalues << it->toString(); QCompleter *c = new QCompleter( svalues ); c->setCompletionMode( QCompleter::PopupCompletion ); le->setCompleter( c ); } if ( editType == QgsVectorLayer::UuidGenerator ) { le->setReadOnly( true ); } le->setValidator( new QgsFieldValidator( le, field ) ); myWidget = le; } if ( te ) { te->setAcceptRichText( true ); myWidget = te; } if ( pte ) { myWidget = pte; } if ( myWidget ) { myWidget->setDisabled( editType == QgsVectorLayer::Immutable ); } } break; case QgsVectorLayer::Hidden: myWidget = 0; break; case QgsVectorLayer::FileName: case QgsVectorLayer::Calendar: { QPushButton *pb = 0; QLineEdit *le = qobject_cast<QLineEdit *>( editor ); if ( le ) { if ( le ) myWidget = le; if ( editor->parent() ) { pb = editor->parent()->findChild<QPushButton *>(); } } else { le = new QLineEdit(); pb = new QPushButton( tr( "..." ) ); QHBoxLayout *hbl = new QHBoxLayout(); hbl->addWidget( le ); hbl->addWidget( pb ); myWidget = new QWidget( parent ); myWidget->setBackgroundRole( QPalette::Window ); myWidget->setAutoFillBackground( true ); myWidget->setLayout( hbl ); } if ( pb ) { if ( editType == QgsVectorLayer::FileName ) connect( pb, SIGNAL( clicked() ), new QgsAttributeEditor( pb ), SLOT( selectFileName() ) ); if ( editType == QgsVectorLayer::Calendar ) connect( pb, SIGNAL( clicked() ), new QgsAttributeEditor( pb ), SLOT( selectDate() ) ); } } break; } setValue( myWidget, vl, idx, value ); return myWidget; }
void StatusBox::doJobQueueStatus() { if (m_iconState) m_iconState->DisplayState("jobqueue"); m_logList->Reset(); QString helpmsg(tr("Job Queue shows any jobs currently in " "MythTV's Job Queue such as a commercial " "detection job.")); if (m_helpText) m_helpText->SetText(helpmsg); if (m_justHelpText) m_justHelpText->SetText(helpmsg); QMap<int, JobQueueEntry> jobs; QMap<int, JobQueueEntry>::Iterator it; JobQueue::GetJobsInQueue(jobs, JOB_LIST_NOT_DONE | JOB_LIST_ERROR | JOB_LIST_RECENT); if (jobs.size()) { QString detail; QString line; for (it = jobs.begin(); it != jobs.end(); ++it) { ProgramInfo pginfo((*it).chanid, (*it).recstartts); if (!pginfo.GetChanID()) continue; detail = QString("%1\n%2 %3 @ %4\n%5 %6 %7 %8") .arg(pginfo.GetTitle()) .arg(pginfo.GetChannelName()) .arg(pginfo.GetChanNum()) .arg(MythDateTimeToString(pginfo.GetRecordingStartTime(), kDateTimeFull | kSimplify)) .arg(tr("Job:")) .arg(JobQueue::JobText((*it).type)) .arg(tr("Status: ")) .arg(JobQueue::StatusText((*it).status)); if ((*it).status != JOB_QUEUED) detail += " (" + (*it).hostname + ')'; if ((*it).schedruntime > QDateTime::currentDateTime()) detail += '\n' + tr("Scheduled Run Time:") + ' ' + MythDateTimeToString((*it).schedruntime, kDateTimeFull | kSimplify); else detail += '\n' + (*it).comment; line = QString("%1 @ %2").arg(pginfo.GetTitle()) .arg(MythDateTimeToString( pginfo.GetRecordingStartTime(), kDateTimeFull | kSimplify)); QString font; if ((*it).status == JOB_ERRORED) font = "error"; else if ((*it).status == JOB_ABORTED) font = "warning"; AddLogLine(line, helpmsg, detail, detail, font, QString("%1").arg((*it).id)); } } else AddLogLine(tr("Job Queue is currently empty."), helpmsg); }
void MainWindow::fillMainWindow() { ui->listUV->clear(); ui->m_tree->clear(); for(int rows = 0; rows != ui->m_gridcursus->rowCount();rows++){ ui->m_gridcursus->removeItem(ui->m_gridcursus->itemAtPosition(rows,0)); ui->m_gridcursus->removeItem(ui->m_gridcursus->itemAtPosition(rows,1)); ui->m_gridcursus->removeItem(ui->m_gridcursus->itemAtPosition(rows,2)); } /* ONGLET DOSSIER */ ui->m_tree->setColumnCount(5); QTreeWidgetItem* headerItem = new QTreeWidgetItem(); headerItem->setText(0,QString("Nom")); headerItem->setText(1,QString("Titre")); headerItem->setText(2,QString("Crédits")); headerItem->setText(3,QString("Catégories")); headerItem->setText(4,QString("Résultat")); ui->m_tree->setHeaderItem(headerItem); ui->m_tree->header()->resizeSection(0, 150); ui->m_tree->header()->resizeSection(1, 300); ui->m_tree->header()->resizeSection(2, 70); ui->m_tree->header()->resizeSection(3, 70); ui->m_tree->header()->resizeSection(4, 40); ui->m_tree->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->m_tree->setSelectionBehavior(QAbstractItemView::SelectRows); ui->m_tree->setSelectionMode(QAbstractItemView::SingleSelection); QList <Dossier *> myDossiers = fac->getDossierDAO()->findAllByEtudiant(currentEtudiant->ID()); QMap<QString, Cursus*> cursusToCompute; for (QList<Dossier *>::const_iterator d = myDossiers.begin(); d != myDossiers.end(); ++d) { QTreeWidgetItem *folderWidget = new QTreeWidgetItem(ui->m_tree,QStringList( (*d)->getTitre() )); QList<Semestre *> mySemestres = fac->getInscriptionDAO()->findSemestresByDossier( (*d)->ID() ); for(QList<Semestre *>::const_iterator s = mySemestres.begin(); s != mySemestres.end(); ++s){ QStringList columns; columns << (*s)->getTitre() << (*s)->getComputedCode() << QString::number( fac->getSemestreDAO()->calculEcts( (*s)->ID() ) ); if((*s)->getCursus()){ columns << (*s)->getCursus()->getFull(); } if((*d)->isCurrent()){ cursusToCompute.insert( (*s)->getCursus()->getCode(), (*s)->getCursus() ); } QTreeWidgetItem *semWidget = new QTreeWidgetItem(folderWidget, columns ); QList<UV *> myUVs = fac->getInscriptionDAO()->findUvsBySemestre( (*s)->ID() ); qDebug()<<myUVs; for(QList<UV *>::const_iterator u = myUVs.begin(); u != myUVs.end(); ++u){ QStringList columns; columns << (*u)->getCode() << (*u)->getTitre() << (*u)->getCreditsString() << (*u)->getCursusString() << fac->getInscriptionDAO()->getResultat((*d)->ID(),(*s)->ID(),(*u)->ID()); QTreeWidgetItem *uvWidget = new QTreeWidgetItem(semWidget, columns); } } } /* ONGLET CURSUS */ int row = 0; for(QMap<QString, Cursus*>::const_iterator i = cursusToCompute.begin(); i != cursusToCompute.end(); ++i){ QProgressBar* pb = new QProgressBar(); QLabel *lab = new QLabel(i.value()->getCode()); pb->setMaximum(i.value()->getEcts()); ui->m_gridcursus->addWidget(lab,row,0); ui->m_gridcursus->addWidget(pb,row,1,1,2); row++; int somme =0; QMap<QString, int> detail = fac->getCursusDAO()->computePercent(i.value()->ID()); for(QMap<QString, int>::const_iterator j = detail.begin(); j != detail.end(); ++j){ QProgressBar* pb = new QProgressBar(); int max = i.value()->getCredits().find(j.key()).value(); int val = j.value(); somme += val; pb->setMaximum( max ); pb->setValue(val); ui->m_gridcursus->addWidget(new QLabel(j.key() + "("+QString::number( val )+"/"+QString::number( max )+")"),row,1 ); ui->m_gridcursus->addWidget(pb,row,2); row++; } pb->setValue(somme); lab->setText( i.value()->getCode() + "("+QString::number( somme )+"/"+QString::number( i.value()->getEcts() )+")" ); } }
bool XMLerSaveFileThread::saveNode ( QXmlStreamWriter &writer, BaseXMLNode *node, qint64 &pos ) { bool result = true; pos += 1; if ( ElementXMLNode *element = qobject_cast<ElementXMLNode *>(node) ) { /* prefix mapping */ if ( element->hasPrefixMapping() ) { QMap<QString,QString> prefixMapping = element->prefixMapping(); QMap<QString,QString>::const_iterator it; for ( it = prefixMapping.begin(); it != prefixMapping.end(); ++it ) writer.writeNamespace ( it.value(), it.key() ); } if ( element->namespaceURI().isEmpty () ) writer.writeStartElement ( element->qName() ); else writer.writeStartElement ( element->namespaceURI(), element->name() ); XMLNodePtrList chlist = element->childs(); XMLNodePtrList::iterator it; for ( it = chlist.begin(); it != chlist.end(); ++it ) { BaseXMLNode *child_node = (*it); result &= saveNode ( writer, child_node, pos ); } writer.writeEndElement(); } else if ( AttrXMLNode *attr = qobject_cast<AttrXMLNode *>(node) ) { if ( attr->namespaceURI().isEmpty() ) writer.writeAttribute ( attr->qName(), attr->value() ); else writer.writeAttribute ( attr->namespaceURI(), attr->name(), attr->value() ); } else if ( DataXMLNode *data = qobject_cast<DataXMLNode *>(node) ) { writer.writeCharacters ( data->data() ); } else if ( DocumentXMLNode *doc = qobject_cast<DocumentXMLNode *>(node) ) { writer.writeStartDocument( doc->version() ); if ( doc->hasPI() ) { const QMap<QString,QString> &pi = _document->processingInstructions(); QMap<QString,QString>::const_iterator it; for ( it = pi.begin(); it != pi.end(); ++it ) { if ( it.key().trimmed().isEmpty() ) continue; writer.writeProcessingInstruction ( it.key(), it.value() ); } } if ( doc->documentNode() ) result &= saveNode ( writer, doc->documentNode(), pos ); writer.writeEndDocument(); } emit progress ( pos ); return result; }
int main(int argc, char **argv) { bool bPromptForBackend = false; bool bBypassAutoDiscovery = false; bool upgradeAllowed = false; bool cmdline_err; MythCommandLineParser cmdline( kCLPOverrideSettingsFile | kCLPOverrideSettings | kCLPWindowed | kCLPNoWindowed | kCLPGetSettings | kCLPQueryVersion | kCLPVerbose | kCLPNoUPnP | #ifdef USING_X11 kCLPDisplay | #endif // USING_X11 kCLPExtra | kCLPGeometry); // Handle --help before QApplication is created, so that // we can print help even if X11 is absent. for (int argpos = 1; argpos < argc; ++argpos) { QString arg(argv[argpos]); if (arg == "-h" || arg == "--help" || arg == "--usage") { ShowUsage(cmdline); return GENERIC_EXIT_OK; } } for (int argpos = 1; argpos < argc; ++argpos) { if (cmdline.PreParse(argc, argv, argpos, cmdline_err)) { if (cmdline_err) return GENERIC_EXIT_INVALID_CMDLINE; if (cmdline.WantsToExit()) return GENERIC_EXIT_OK; } } #ifdef Q_WS_MACX // Without this, we can't set focus to any of the CheckBoxSetting, and most // of the MythPushButton widgets, and they don't use the themed background. QApplication::setDesktopSettingsAware(false); #endif QApplication a(argc, argv); QCoreApplication::setApplicationName(MYTH_APPNAME_MYTHFRONTEND); QString pluginname; QFileInfo finfo(a.argv()[0]); QString binname = finfo.baseName(); VERBOSE(VB_IMPORTANT, QString("%1 version: %2 [%3] www.mythtv.org") .arg(MYTH_APPNAME_MYTHFRONTEND) .arg(MYTH_SOURCE_PATH) .arg(MYTH_SOURCE_VERSION)); bool ResetSettings = false; if (binname.toLower() != "mythfrontend") pluginname = binname; for (int argpos = 1; argpos < a.argc(); ++argpos) { if (!strcmp(a.argv()[argpos],"--prompt") || !strcmp(a.argv()[argpos],"-p" )) { bPromptForBackend = true; } else if (!strcmp(a.argv()[argpos],"--disable-autodiscovery") || !strcmp(a.argv()[argpos],"-d" )) { bBypassAutoDiscovery = true; } else if (!strcmp(a.argv()[argpos],"-l") || !strcmp(a.argv()[argpos],"--logfile")) { if (a.argc()-1 > argpos) { logfile = a.argv()[argpos+1]; if (logfile.startsWith('-')) { cerr << "Invalid or missing argument" " to -l/--logfile option\n"; return GENERIC_EXIT_INVALID_CMDLINE; } else { ++argpos; } } else { cerr << "Missing argument to -l/--logfile option\n"; return GENERIC_EXIT_INVALID_CMDLINE; } } else if (cmdline.Parse(a.argc(), a.argv(), argpos, cmdline_err)) { if (cmdline_err) return GENERIC_EXIT_INVALID_CMDLINE; if (cmdline.WantsToExit()) return GENERIC_EXIT_OK; } } QMap<QString,QString> settingsOverride = cmdline.GetSettingsOverride(); if (logfile.size()) { if (log_rotate(1) < 0) cerr << "cannot open logfile; using stdout/stderr" << endl; else { VERBOSE(VB_IMPORTANT, QString("%1 version: %2 [%3] www.mythtv.org") .arg(MYTH_APPNAME_MYTHFRONTEND) .arg(MYTH_SOURCE_PATH) .arg(MYTH_SOURCE_VERSION)); signal(SIGHUP, &log_rotate_handler); } } if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) cerr << "Unable to ignore SIGPIPE\n"; if (!cmdline.GetDisplay().isEmpty()) { MythUIHelper::SetX11Display(cmdline.GetDisplay()); } if (!cmdline.GetGeometry().isEmpty()) { MythUIHelper::ParseGeometryOverride(cmdline.GetGeometry()); } CleanupGuard callCleanup(cleanup); gContext = new MythContext(MYTH_BINARY_VERSION); if (cmdline.IsUPnPEnabled()) { g_pUPnp = new MediaRenderer(); if (!g_pUPnp->initialized()) { delete g_pUPnp; g_pUPnp = NULL; } } // Override settings as early as possible to cover bootstrapped screens // such as the language prompt settingsOverride = cmdline.GetSettingsOverride(); if (settingsOverride.size()) { QMap<QString, QString>::iterator it; for (it = settingsOverride.begin(); it != settingsOverride.end(); ++it) { VERBOSE(VB_IMPORTANT, QString("Setting '%1' being forced to '%2'") .arg(it.key()).arg(*it)); gCoreContext->OverrideSettingForSession(it.key(), *it); } } if (!gContext->Init(true, bPromptForBackend, bBypassAutoDiscovery)) { VERBOSE(VB_IMPORTANT, "Failed to init MythContext, exiting."); return GENERIC_EXIT_NO_MYTHCONTEXT; } if (!GetMythDB()->HaveSchema()) { if (!InitializeMythSchema()) return GENERIC_EXIT_DB_ERROR; } for(int argpos = 1; argpos < a.argc(); ++argpos) { if (!strcmp(a.argv()[argpos],"-l") || !strcmp(a.argv()[argpos],"--logfile")) { // Arg processing for logfile already done (before MythContext) ++argpos; } else if (!strcmp(a.argv()[argpos],"-v") || !strcmp(a.argv()[argpos],"--verbose")) { // Arg processing for verbose already done (before MythContext) ++argpos; } else if (!strcmp(a.argv()[argpos],"-r") || !strcmp(a.argv()[argpos],"--reset")) { ResetSettings = true; } else if (!strcmp(a.argv()[argpos],"--prompt") || !strcmp(a.argv()[argpos],"-p" )) { } else if (!strcmp(a.argv()[argpos],"--disable-autodiscovery") || !strcmp(a.argv()[argpos],"-d" )) { } else if (!strcmp(a.argv()[argpos],"--upgrade-schema") || !strcmp(a.argv()[argpos],"-u" )) { upgradeAllowed = true; } else if (cmdline.Parse(a.argc(), a.argv(), argpos, cmdline_err)) { if (cmdline_err) { return GENERIC_EXIT_INVALID_CMDLINE; } if (cmdline.WantsToExit()) { return GENERIC_EXIT_OK; } } else if ((argpos + 1 == a.argc()) && (!QString(a.argv()[argpos]).startsWith('-'))) { pluginname = a.argv()[argpos]; } else { cerr << "Invalid argument: " << a.argv()[argpos] << endl; ShowUsage(cmdline); return GENERIC_EXIT_INVALID_CMDLINE; } } QStringList settingsQuery = cmdline.GetSettingsQuery(); if (!settingsQuery.empty()) { QStringList::const_iterator it = settingsQuery.begin(); for (; it != settingsQuery.end(); ++it) { QString value = gCoreContext->GetSetting(*it); QString out = QString("\tSettings Value : %1 = %2") .arg(*it).arg(value); cout << out.toLocal8Bit().constData() << endl; } return GENERIC_EXIT_OK; } QString fileprefix = GetConfDir(); QDir dir(fileprefix); if (!dir.exists()) dir.mkdir(fileprefix); if (ResetSettings) { AppearanceSettings as; as.Save(); gCoreContext->SaveSetting("Theme", DEFAULT_UI_THEME); gCoreContext->SaveSetting("Language", ""); gCoreContext->SaveSetting("Country", ""); return GENERIC_EXIT_OK; } setuid(getuid()); VERBOSE(VB_IMPORTANT, QString("Enabled verbose msgs: %1").arg(verboseString)); LCD::SetupLCD(); if (LCD *lcd = LCD::Get()) lcd->setupLEDs(RemoteGetRecordingMask); MythTranslation::load("mythfrontend"); QString themename = gCoreContext->GetSetting("Theme", DEFAULT_UI_THEME); QString themedir = GetMythUI()->FindThemeDir(themename); if (themedir.isEmpty()) { VERBOSE(VB_IMPORTANT, QString("Couldn't find theme '%1'") .arg(themename)); return GENERIC_EXIT_NO_THEME; } GetMythUI()->LoadQtConfig(); themename = gCoreContext->GetSetting("Theme", DEFAULT_UI_THEME); themedir = GetMythUI()->FindThemeDir(themename); if (themedir.isEmpty()) { VERBOSE(VB_IMPORTANT, QString("Couldn't find theme '%1'") .arg(themename)); return GENERIC_EXIT_NO_THEME; } MythMainWindow *mainWindow = GetMythMainWindow(); mainWindow->Init(); mainWindow->setWindowTitle(QObject::tr("MythTV Frontend")); // We must reload the translation after a language change and this // also means clearing the cached/loaded theme strings, so reload the // theme which also triggers a translation reload if (LanguageSelection::prompt()) { if (!reloadTheme()) return GENERIC_EXIT_NO_THEME; } if (!UpgradeTVDatabaseSchema(upgradeAllowed)) { VERBOSE(VB_IMPORTANT, "Couldn't upgrade database to new schema, exiting."); return GENERIC_EXIT_DB_OUTOFDATE; } WriteDefaults(); // Refresh Global/Main Menu keys after DB update in case there was no DB // when they were written originally mainWindow->ResetKeys(); InitJumpPoints(); internal_media_init(); CleanupMyOldInUsePrograms(); pmanager = new MythPluginManager(); gContext->SetPluginManager(pmanager); if (pluginname.size()) { if (pmanager->run_plugin(pluginname) || pmanager->run_plugin("myth" + pluginname)) { qApp->exec(); return GENERIC_EXIT_OK; } else return GENERIC_EXIT_INVALID_CMDLINE; } MediaMonitor *mon = MediaMonitor::GetMediaMonitor(); if (mon) { mon->StartMonitoring(); mainWindow->installEventFilter(mon); } NetworkControl *networkControl = NULL; if (gCoreContext->GetNumSetting("NetworkControlEnabled", 0)) { int networkPort = gCoreContext->GetNumSetting("NetworkControlPort", 6545); networkControl = new NetworkControl(); if (!networkControl->listen(QHostAddress::Any,networkPort)) VERBOSE(VB_IMPORTANT, QString("NetworkControl failed to bind to port %1.") .arg(networkPort)); } #ifdef __linux__ #ifdef CONFIG_BINDINGS_PYTHON HardwareProfile *profile = new HardwareProfile(); if (profile && profile->NeedsUpdate()) profile->SubmitProfile(); delete profile; #endif #endif if (!RunMenu(themedir, themename) && !resetTheme(themedir, themename)) { return GENERIC_EXIT_NO_THEME; } #ifndef _MSC_VER // Setup handler for USR1 signals to reload theme signal(SIGUSR1, &signal_USR1_handler); // Setup handler for USR2 signals to restart LIRC signal(SIGUSR2, &signal_USR2_handler); #endif ThemeUpdateChecker *themeUpdateChecker = NULL; if (gCoreContext->GetNumSetting("ThemeUpdateNofications", 1)) themeUpdateChecker = new ThemeUpdateChecker(); MythSystemEventHandler *sysEventHandler = new MythSystemEventHandler(); GetMythMainWindow()->RegisterSystemEventHandler(sysEventHandler); BackendConnectionManager bcm; PreviewGeneratorQueue::CreatePreviewGeneratorQueue( PreviewGenerator::kRemote, 50, 60); int ret = qApp->exec(); PreviewGeneratorQueue::TeardownPreviewGeneratorQueue(); if (themeUpdateChecker) delete themeUpdateChecker; delete sysEventHandler; pmanager->DestroyAllPlugins(); if (mon) mon->deleteLater(); delete networkControl; DestroyMythMainWindow(); return ret; }
void TransitionHandler::updateTransitionParams(QString type, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml) { QScopedPointer<Mlt::Field> field(m_tractor->field()); field->lock(); double fps = m_tractor->get_fps(); mlt_service nextservice = mlt_service_get_producer(field->get_service()); mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice); QString resource = mlt_properties_get(properties, "mlt_service"); int in_pos = (int) in.frames(fps); int out_pos = (int) out.frames(fps) - 1; mlt_service_type mlt_type = mlt_service_identify( nextservice ); while (mlt_type == transition_type) { mlt_transition tr = (mlt_transition) nextservice; int currentTrack = mlt_transition_get_b_track(tr); int currentBTrack = mlt_transition_get_a_track(tr); int currentIn = (int) mlt_transition_get_in(tr); int currentOut = (int) mlt_transition_get_out(tr); // //qDebug()<<"Looking for transition : " << currentIn <<'x'<<currentOut<< ", OLD oNE: "<<in_pos<<'x'<<out_pos; if (resource == type && b_track == currentTrack && currentIn == in_pos && currentOut == out_pos) { QMap<QString, QString> map = getTransitionParamsFromXml(xml); QMap<QString, QString>::Iterator it; QString key; mlt_properties transproperties = MLT_TRANSITION_PROPERTIES(tr); QString currentId = mlt_properties_get(transproperties, "kdenlive_id"); if (currentId != xml.attribute(QStringLiteral("id"))) { // The transition ID is not the same, so reset all properties mlt_properties_set(transproperties, "kdenlive_id", xml.attribute(QStringLiteral("id")).toUtf8().constData()); // Cleanup previous properties QStringList permanentProps; permanentProps << QStringLiteral("factory") << QStringLiteral("kdenlive_id") << QStringLiteral("mlt_service") << QStringLiteral("mlt_type") << QStringLiteral("in"); permanentProps << QStringLiteral("out") << QStringLiteral("a_track") << QStringLiteral("b_track"); for (int i = 0; i < mlt_properties_count(transproperties); ++i) { QString propName = mlt_properties_get_name(transproperties, i); if (!propName.startsWith('_') && ! permanentProps.contains(propName)) { mlt_properties_set(transproperties, propName.toUtf8().constData(), ""); } } } mlt_properties_set_int(transproperties, "force_track", xml.attribute(QStringLiteral("force_track")).toInt()); mlt_properties_set_int(transproperties, "automatic", xml.attribute(QStringLiteral("automatic"), QStringLiteral("0")).toInt()); if (currentBTrack != a_track) { mlt_properties_set_int(transproperties, "a_track", a_track); } for (it = map.begin(); it != map.end(); ++it) { key = it.key(); mlt_properties_set(transproperties, key.toUtf8().constData(), it.value().toUtf8().constData()); //qDebug() << " ------ UPDATING TRANS PARAM: " << key.toUtf8().constData() << ": " << it.value().toUtf8().constData(); //filter->set("kdenlive_id", id); } break; } nextservice = mlt_service_producer(nextservice); if (nextservice == NULL) break; properties = MLT_SERVICE_PROPERTIES(nextservice); mlt_type = mlt_service_identify( nextservice ); resource = mlt_properties_get(properties, "mlt_service"); } field->unlock(); //askForRefresh(); //if (m_isBlocked == 0) m_mltConsumer->set("refresh", 1); }
void Incidence::setFields(const KCal::Incidence *incidence) { KolabBase::setFields(incidence); if(incidence->doesFloat()) { // This is a floating event. Don't timezone move this one mFloatingStatus = AllDay; setStartDate(incidence->dtStart().date()); } else { mFloatingStatus = HasTime; setStartDate(localToUTC(incidence->dtStart())); } setSummary(incidence->summary()); setLocation(incidence->location()); // Alarm mHasAlarm = false; // Will be set to true, if we actually have one if(incidence->isAlarmEnabled()) { const KCal::Alarm::List &alarms = incidence->alarms(); if(!alarms.isEmpty()) { const KCal::Alarm *alarm = alarms.first(); if(alarm->hasStartOffset()) { int dur = alarm->startOffset().asSeconds(); setAlarm((float)dur / 60.0); } } } Email org(incidence->organizer().name(), incidence->organizer().email()); setOrganizer(org); // Attendees: KCal::Attendee::List attendees = incidence->attendees(); KCal::Attendee::List::ConstIterator it; for(it = attendees.begin(); it != attendees.end(); ++it) { KCal::Attendee *kcalAttendee = *it; Attendee attendee; attendee.displayName = kcalAttendee->name(); attendee.smtpAddress = kcalAttendee->email(); attendee.status = attendeeStatusToString(kcalAttendee->status()); attendee.requestResponse = kcalAttendee->RSVP(); // TODO: KCal::Attendee::mFlag is not accessible // attendee.invitationSent = kcalAttendee->mFlag; // DF: Hmm? mFlag is set to true and never used at all.... Did you mean another field? attendee.role = attendeeRoleToString(kcalAttendee->role()); attendee.delegate = kcalAttendee->delegate(); attendee.delegator = kcalAttendee->delegator(); addAttendee(attendee); } mAttachments.clear(); // Attachments KCal::Attachment::List attachments = incidence->attachments(); KCal::Attachment::List::ConstIterator it2; for(it2 = attachments.begin(); it2 != attachments.end(); ++it2) { KCal::Attachment *a = *it2; mAttachments.push_back(a); } if(incidence->doesRecur()) { setRecurrence(incidence->recurrence()); mRecurrence.exclusions = incidence->recurrence()->exDates(); } // Handle the scheduling ID if(incidence->schedulingID() == incidence->uid()) { // There is no scheduling ID setInternalUID(QString::null); } else { // We've internally been using a different uid, so save that as the // temporary (internal) uid and restore the original uid, the one that // is used in the folder and the outside world setUid(incidence->schedulingID()); setInternalUID(incidence->uid()); } // Unhandled tags and other custom properties (see libkcal/customproperties.h) const QMap<QCString, QString> map = incidence->customProperties(); QMap<QCString, QString>::ConstIterator cit = map.begin(); for(; cit != map.end() ; ++cit) { Custom c; c.key = cit.key(); c.value = cit.data(); mCustomList.append(c); } }
Response::ResponseCode Server_ProtocolHandler::cmdLogin(const Command_Login &cmd, ResponseContainer &rc) { QString userName = QString::fromStdString(cmd.user_name()).simplified(); QString clientId = QString::fromStdString(cmd.clientid()).simplified(); QString clientVersion = QString::fromStdString(cmd.clientver()).simplified(); if (userInfo != 0) return Response::RespContextError; // check client feature set against server feature set FeatureSet features; QMap<QString, bool> receivedClientFeatures; QMap<QString, bool> missingClientFeatures; for (int i = 0; i < cmd.clientfeatures().size(); ++i) receivedClientFeatures.insert(QString::fromStdString(cmd.clientfeatures(i)).simplified(), false); missingClientFeatures = features.identifyMissingFeatures(receivedClientFeatures, server->getServerRequiredFeatureList()); if (!missingClientFeatures.isEmpty()) { if (features.isRequiredFeaturesMissing(missingClientFeatures, server->getServerRequiredFeatureList())) { Response_Login *re = new Response_Login; re->set_denied_reason_str("Client upgrade required"); QMap<QString, bool>::iterator i; for (i = missingClientFeatures.begin(); i != missingClientFeatures.end(); ++i) re->add_missing_features(i.key().toStdString().c_str()); rc.setResponseExtension(re); return Response::RespClientUpdateRequired; } } QString reasonStr; int banSecondsLeft = 0; AuthenticationResult res = server->loginUser(this, userName, QString::fromStdString(cmd.password()), reasonStr, banSecondsLeft, clientId, clientVersion); switch (res) { case UserIsBanned: { Response_Login *re = new Response_Login; re->set_denied_reason_str(reasonStr.toStdString()); if (banSecondsLeft != 0) re->set_denied_end_time(QDateTime::currentDateTime().addSecs(banSecondsLeft).toTime_t()); rc.setResponseExtension(re); return Response::RespUserIsBanned; } case NotLoggedIn: return Response::RespWrongPassword; case WouldOverwriteOldSession: return Response::RespWouldOverwriteOldSession; case UsernameInvalid: { Response_Login *re = new Response_Login; re->set_denied_reason_str(reasonStr.toStdString()); rc.setResponseExtension(re); return Response::RespUsernameInvalid; } case RegistrationRequired: return Response::RespRegistrationRequired; case ClientIdRequired: return Response::RespClientIdRequired; case UserIsInactive: return Response::RespAccountNotActivated; default: authState = res; } userName = QString::fromStdString(userInfo->name()); Event_ServerMessage event; event.set_message(server->getLoginMessage().toStdString()); rc.enqueuePostResponseItem(ServerMessage::SESSION_EVENT, prepareSessionEvent(event)); Response_Login *re = new Response_Login; re->mutable_user_info()->CopyFrom(copyUserInfo(true)); if (authState == PasswordRight) { QMapIterator<QString, ServerInfo_User> buddyIterator(databaseInterface->getBuddyList(userName)); while (buddyIterator.hasNext()) re->add_buddy_list()->CopyFrom(buddyIterator.next().value()); QMapIterator<QString, ServerInfo_User> ignoreIterator(databaseInterface->getIgnoreList(userName)); while (ignoreIterator.hasNext()) re->add_ignore_list()->CopyFrom(ignoreIterator.next().value()); } // return to client any missing features the server has that the client does not if (!missingClientFeatures.isEmpty()) { QMap<QString, bool>::iterator i; for (i = missingClientFeatures.begin(); i != missingClientFeatures.end(); ++i) re->add_missing_features(i.key().toStdString().c_str()); } joinPersistentGames(rc); rc.setResponseExtension(re); return Response::RespOk; }
void LS3Datastore::cleanFieldContents(QMap<QString, QVariant> &data) { for (QMap<QString, QVariant>::iterator it=data.begin(); it!=data.end(); ++it) { cleanFieldContents(it.key(), it.value()); } }
FiffCov FiffCov::regularize(const FiffInfo& p_info, double p_fRegMag, double p_fRegGrad, double p_fRegEeg, bool p_bProj, QStringList p_exclude) const { FiffCov cov(*this); if(p_exclude.size() == 0) { p_exclude = p_info.bads; for(qint32 i = 0; i < cov.bads.size(); ++i) if(!p_exclude.contains(cov.bads[i])) p_exclude << cov.bads[i]; } //Allways exclude all STI channels from covariance computation for(int i=0; i<p_info.chs.size(); i++) if(p_info.chs[i].kind == FIFFV_STIM_CH) p_exclude << p_info.chs[i].ch_name; RowVectorXi sel_eeg = p_info.pick_types(false, true, false, defaultQStringList, p_exclude); RowVectorXi sel_mag = p_info.pick_types(QString("mag"), false, false, defaultQStringList, p_exclude); RowVectorXi sel_grad = p_info.pick_types(QString("grad"), false, false, defaultQStringList, p_exclude); QStringList info_ch_names = p_info.ch_names; QStringList ch_names_eeg, ch_names_mag, ch_names_grad; for(qint32 i = 0; i < sel_eeg.size(); ++i) ch_names_eeg << info_ch_names[sel_eeg(i)]; for(qint32 i = 0; i < sel_mag.size(); ++i) ch_names_mag << info_ch_names[sel_mag(i)]; for(qint32 i = 0; i < sel_grad.size(); ++i) ch_names_grad << info_ch_names[sel_grad(i)]; // This actually removes bad channels from the cov, which is not backward // compatible, so let's leave all channels in FiffCov cov_good = cov.pick_channels(info_ch_names, p_exclude); QStringList ch_names = cov_good.names; std::vector<qint32> idx_eeg, idx_mag, idx_grad; for(qint32 i = 0; i < ch_names.size(); ++i) { if(ch_names_eeg.contains(ch_names[i])) idx_eeg.push_back(i); else if(ch_names_mag.contains(ch_names[i])) idx_mag.push_back(i); else if(ch_names_grad.contains(ch_names[i])) idx_grad.push_back(i); } MatrixXd C(cov_good.data); if((unsigned) C.rows() != idx_eeg.size() + idx_mag.size() + idx_grad.size()) printf("Error in FiffCov::regularize: Channel dimensions do not fit.\n");//ToDo Throw QList<FiffProj> t_listProjs; if(p_bProj) { t_listProjs = p_info.projs + cov_good.projs; FiffProj::activate_projs(t_listProjs); } //Build regularization MAP QMap<QString, QPair<double, std::vector<qint32> > > regData; regData.insert("EEG", QPair<double, std::vector<qint32> >(p_fRegEeg, idx_eeg)); regData.insert("MAG", QPair<double, std::vector<qint32> >(p_fRegMag, idx_mag)); regData.insert("GRAD", QPair<double, std::vector<qint32> >(p_fRegGrad, idx_grad)); // //Regularize // QMap<QString, QPair<double, std::vector<qint32> > >::Iterator it; for(it = regData.begin(); it != regData.end(); ++it) { QString desc(it.key()); double reg = it.value().first; std::vector<qint32> idx = it.value().second; if(idx.size() == 0 || reg == 0.0) printf("\tNothing to regularize within %s data.\n", desc.toLatin1().constData()); else { printf("\tRegularize %s: %f\n", desc.toLatin1().constData(), reg); MatrixXd this_C(idx.size(), idx.size()); for(quint32 i = 0; i < idx.size(); ++i) for(quint32 j = 0; j < idx.size(); ++j) this_C(i,j) = cov_good.data(idx[i], idx[j]); MatrixXd U; qint32 ncomp; if(p_bProj) { QStringList this_ch_names; for(quint32 k = 0; k < idx.size(); ++k) this_ch_names << ch_names[idx[k]]; MatrixXd P; ncomp = FiffProj::make_projector(t_listProjs, this_ch_names, P); //ToDo: Synchronize with mne-python and debug JacobiSVD<MatrixXd> svd(P, ComputeFullU); //Sort singular values and singular vectors VectorXd t_s = svd.singularValues(); MatrixXd t_U = svd.matrixU(); MNEMath::sort<double>(t_s, t_U); U = t_U.block(0,0, t_U.rows(), t_U.cols()-ncomp); if (ncomp > 0) { printf("\tCreated an SSP operator for %s (dimension = %d).\n", desc.toLatin1().constData(), ncomp); this_C = U.transpose() * (this_C * U); } } double sigma = this_C.diagonal().mean(); this_C.diagonal() = this_C.diagonal().array() + reg * sigma; // modify diag inplace if(p_bProj && ncomp > 0) this_C = U * (this_C * U.transpose()); for(qint32 i = 0; i < this_C.rows(); ++i) for(qint32 j = 0; j < this_C.cols(); ++j) C(idx[i],idx[j]) = this_C(i,j); } } // Put data back in correct locations RowVectorXi idx = FiffInfo::pick_channels(cov.names, info_ch_names, p_exclude); for(qint32 i = 0; i < idx.size(); ++i) for(qint32 j = 0; j < idx.size(); ++j) cov.data(idx[i], idx[j]) = C(i, j); return cov; }
bool KStandardDirs::addCustomized(KConfig *config) { if(addedCustoms && !d->checkRestrictions) // there are already customized entries return false; // we just quit and hope they are the right ones // save the numbers of config directories. If this changes, // we will return true to give KConfig a chance to reparse uint configdirs = resourceDirs("config").count(); // Remember original group QString oldGroup = config->group(); if(!addedCustoms) { // We only add custom entries once addedCustoms = true; // reading the prefixes in QString group = QString::fromLatin1("Directories"); config->setGroup(group); QString kioskAdmin = config->readEntry("kioskAdmin"); if(!kioskAdmin.isEmpty() && !kde_kiosk_admin) { int i = kioskAdmin.find(':'); QString user = kioskAdmin.left(i); QString host = kioskAdmin.mid(i + 1); KUser thisUser; char hostname[256]; hostname[0] = '\0'; if(!gethostname(hostname, 255)) hostname[sizeof(hostname) - 1] = '\0'; if((user == thisUser.loginName()) && (host.isEmpty() || (host == hostname))) { kde_kiosk_admin = true; } } bool readProfiles = true; if(kde_kiosk_admin && !QCString(getenv("KDE_KIOSK_NO_PROFILES")).isEmpty()) readProfiles = false; QString userMapFile = config->readEntry("userProfileMapFile"); QString profileDirsPrefix = config->readEntry("profileDirsPrefix"); if(!profileDirsPrefix.isEmpty() && !profileDirsPrefix.endsWith("/")) profileDirsPrefix.append('/'); QStringList profiles; if(readProfiles) profiles = lookupProfiles(userMapFile); QString profile; bool priority = false; while(true) { config->setGroup(group); QStringList list = config->readListEntry("prefixes"); for(QStringList::ConstIterator it = list.begin(); it != list.end(); ++it) { addPrefix(*it, priority); addXdgConfigPrefix(*it + "/etc/xdg", priority); addXdgDataPrefix(*it + "/share", priority); } // If there are no prefixes defined, check if there is a directory // for this profile under <profileDirsPrefix> if(list.isEmpty() && !profile.isEmpty() && !profileDirsPrefix.isEmpty()) { QString dir = profileDirsPrefix + profile; addPrefix(dir, priority); addXdgConfigPrefix(dir + "/etc/xdg", priority); addXdgDataPrefix(dir + "/share", priority); } // iterating over all entries in the group Directories // to find entries that start with dir_$type QMap< QString, QString > entries = config->entryMap(group); for(QMap< QString, QString >::ConstIterator it2 = entries.begin(); it2 != entries.end(); it2++) { QString key = it2.key(); if(key.startsWith("dir_")) { // generate directory list, there may be more than 1. QStringList dirs = QStringList::split(',', *it2); QStringList::Iterator sIt(dirs.begin()); QString resType = key.mid(4, key.length()); for(; sIt != dirs.end(); ++sIt) { addResourceDir(resType.latin1(), *sIt, priority); } } } if(profiles.isEmpty()) break; profile = profiles.back(); group = QString::fromLatin1("Directories-%1").arg(profile); profiles.pop_back(); priority = true; } } // Process KIOSK restrictions. if(!kde_kiosk_admin || QCString(getenv("KDE_KIOSK_NO_RESTRICTIONS")).isEmpty()) { config->setGroup("KDE Resource Restrictions"); QMap< QString, QString > entries = config->entryMap("KDE Resource Restrictions"); for(QMap< QString, QString >::ConstIterator it2 = entries.begin(); it2 != entries.end(); it2++) { QString key = it2.key(); if(!config->readBoolEntry(key, true)) { d->restrictionsActive = true; d->restrictions.insert(key.latin1(), &d->restrictionsActive); // Anything will do dircache.remove(key.latin1()); } } } config->setGroup(oldGroup); // check if the number of config dirs changed bool configDirsChanged = (resourceDirs("config").count() != configdirs); // If the config dirs changed, we check kiosk restrictions again. d->checkRestrictions = configDirsChanged; // return true if the number of config dirs changed: reparse config file return configDirsChanged; }
RgLineVectorLayerSettingsWidget::RgLineVectorLayerSettingsWidget( RgLineVectorLayerSettings *s, QWidget* parent ) : QWidget( parent ) { // create base widgets; QTabWidget *tab = new QTabWidget( this ); QVBoxLayout *v = new QVBoxLayout( this ); v->addWidget( tab ); // transportation layer QFrame *frame = new QFrame( this ); tab->addTab( frame, tr( "Transportation layer" ) ); v = new QVBoxLayout( frame ); QLabel *l = new QLabel( tr( "Layer" ), frame ); mcbLayers = new QComboBox( frame ); QHBoxLayout *h = new QHBoxLayout(); h->addWidget( l ); h->addWidget( mcbLayers ); v->addLayout( h ); h = new QHBoxLayout(); l = new QLabel( tr( "Direction field" ), frame ); mcbDirection = new QComboBox( frame ); h->addWidget( l ); h->addWidget( mcbDirection ); v->addLayout( h ); h = new QHBoxLayout(); h->addWidget( new QLabel( tr( "Value for forward direction" ), frame ) ); mleFirstPointToLastPointDirection = new QLineEdit( s->mFirstPointToLastPointDirectionVal, frame ); h->addWidget( mleFirstPointToLastPointDirection ); v->addLayout( h ); h = new QHBoxLayout(); h->addWidget( new QLabel( tr( "Value for reverse direction" ), frame ) ); mleLastPointToFirstPointDirection = new QLineEdit( s->mLastPointToFirstPointDirectionVal, frame ); h->addWidget( mleLastPointToFirstPointDirection ); v->addLayout( h ); h = new QHBoxLayout(); h->addWidget( new QLabel( tr( "Value two-way direction" ), frame ) ); mleBothDirection = new QLineEdit( s->mBothDirectionVal, frame ); h->addWidget( mleBothDirection ); v->addLayout( h ); h = new QHBoxLayout(); l = new QLabel( tr( "Speed field" ), frame ); mcbSpeed = new QComboBox( frame ); h->addWidget( l ); h->addWidget( mcbSpeed ); mcbUnitOfSpeed = new QComboBox( this ); h->addWidget( mcbUnitOfSpeed ); mcbUnitOfSpeed->insertItem( 0, tr( "km/h" ) ); mcbUnitOfSpeed->insertItem( 0, tr( "m/s" ) ); v->addLayout( h ); frame = new QFrame( tab ); tab->addTab( frame, tr( "Default settings" ) ); v = new QVBoxLayout( frame ); h = new QHBoxLayout(); l = new QLabel( tr( "Direction" ), frame ); mcbDirectionDefault = new QComboBox( frame ); mcbDirectionDefault->insertItem( 0, tr( "Two-way direction" ) ); mcbDirectionDefault->insertItem( 1, tr( "Forward direction" ) ); mcbDirectionDefault->insertItem( 2, tr( "Reverse direction" ) ); connect( mcbLayers, SIGNAL( currentIndexChanged( int ) ), this, SLOT( on_mcbLayers_selectItem() ) ); h->addWidget( l ); h->addWidget( mcbDirectionDefault ); v->addLayout( h ); h = new QHBoxLayout(); l = new QLabel( tr( "Cost" ), frame ); h->addWidget( l ); l = new QLabel( tr( "Line lengths" ), frame ); h->addWidget( l ); v->addLayout( h ); h = new QHBoxLayout(); l = new QLabel( tr( "Speed" ), frame ); msbSpeedDefault = new QSpinBox( frame ); msbSpeedDefault->setMinimum( 1 ); msbSpeedDefault->setMaximum( 10000000 ); h->addWidget( l ); h->addWidget( msbSpeedDefault ); v->addLayout( h ); // fill list of layers QMap<QString, QgsMapLayer*> mapLayers = QgsMapLayerRegistry::instance()->mapLayers(); QMap<QString, QgsMapLayer*>::iterator layer_it = mapLayers.begin(); for ( ; layer_it != mapLayers.end(); ++layer_it ) { QgsVectorLayer* vl = dynamic_cast<QgsVectorLayer*>( layer_it.value() ); if ( !vl ) continue; if ( vl->wkbType() == QGis::WKBLineString || vl->wkbType() == QGis::WKBMultiLineString ) mcbLayers->insertItem( 0, vl->name() ); } //sets current settings msbSpeedDefault->setValue( static_cast<int>( s->mDefaultSpeed ) ); int idx = mcbLayers->findText( s->mLayer ); if ( idx != -1 ) { mcbLayers->setCurrentIndex( idx ); } idx = mcbDirection->findText( s->mDirection ); if ( idx != -1 ) mcbDirection->setCurrentIndex( idx ); idx = mcbSpeed->findText( s->mSpeed ); if ( idx != -1 ) mcbSpeed->setCurrentIndex( idx ); switch ( s->mDefaultDirection ) { case RgLineVectorLayerSettings::Both: mcbDirectionDefault->setCurrentIndex( 0 ); break; case RgLineVectorLayerSettings::FirstPointToLastPoint: mcbDirectionDefault->setCurrentIndex( 1 ); break; case RgLineVectorLayerSettings::LastPointToFirstPoint: mcbDirectionDefault->setCurrentIndex( 2 ); break; } if ( s->mSpeedUnitName == "km/h" ) mcbUnitOfSpeed->setCurrentIndex( 1 ); else if ( s->mSpeedUnitName == "m/s" ) mcbUnitOfSpeed->setCurrentIndex( 0 ); } // RgLineVectorLayerSettingsWidget::RgLineVectorLayerSettingsWidget()
int main(int argc, char *argv[]) { int quiet = 0; MythJobQueueCommandLineParser cmdline; if (!cmdline.Parse(argc, argv)) { cmdline.PrintHelp(); return GENERIC_EXIT_INVALID_CMDLINE; } if (cmdline.toBool("showhelp")) { cmdline.PrintHelp(); return GENERIC_EXIT_OK; } if (cmdline.toBool("showversion")) { cmdline.PrintVersion(); return GENERIC_EXIT_OK; } QCoreApplication a(argc, argv); QMap<QString, QString> settingsOverride = cmdline.GetSettingsOverride(); bool daemonize = false; QCoreApplication::setApplicationName(MYTH_APPNAME_MYTHJOBQUEUE); QString filename; if (cmdline.toBool("verbose")) if (parse_verbose_arg(cmdline.toString("verbose")) == GENERIC_EXIT_INVALID_CMDLINE) return GENERIC_EXIT_INVALID_CMDLINE; if (cmdline.toBool("quiet")) { quiet = cmdline.toUInt("quiet"); if (quiet > 1) { print_verbose_messages = VB_NONE; parse_verbose_arg("none"); } } int facility = cmdline.GetSyslogFacility(); bool dblog = !cmdline.toBool("nodblog"); if (cmdline.toBool("pidfile")) pidfile = cmdline.toString("pidfile"); if (cmdline.toBool("daemon")) daemonize = true; CleanupGuard callCleanup(cleanup); logfile = cmdline.GetLogFilePath(); logStart(logfile, quiet, facility, dblog); ofstream pidfs; if (pidfile.size()) { pidfs.open(pidfile.toAscii().constData()); if (!pidfs) { VERBOSE(VB_IMPORTANT, LOC_ERR + "Could not open pid file" + ENO); return GENERIC_EXIT_PERMISSIONS_ERROR; } } if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) VERBOSE(VB_IMPORTANT, LOC_WARN + "Unable to ignore SIGPIPE"); if (daemonize && (daemon(0, 1) < 0)) { VERBOSE(VB_IMPORTANT, LOC_ERR + "Failed to daemonize" + ENO); return GENERIC_EXIT_DAEMONIZING_ERROR; } if (pidfs) { pidfs << getpid() << endl; pidfs.close(); } VERBOSE(VB_IMPORTANT, QString("%1 version: %2 [%3] www.mythtv.org") .arg(MYTH_APPNAME_MYTHJOBQUEUE) .arg(MYTH_SOURCE_PATH) .arg(MYTH_SOURCE_VERSION)); gContext = new MythContext(MYTH_BINARY_VERSION); if (!gContext->Init(false)) { VERBOSE(VB_IMPORTANT, LOC_ERR + "Failed to init MythContext, exiting."); return GENERIC_EXIT_NO_MYTHCONTEXT; } if (settingsOverride.size()) { QMap<QString, QString>::iterator it; for (it = settingsOverride.begin(); it != settingsOverride.end(); ++it) { VERBOSE(VB_IMPORTANT, QString("Setting '%1' being forced to '%2'") .arg(it.key()).arg(*it)); gCoreContext->OverrideSettingForSession(it.key(), *it); } } if (!gCoreContext->ConnectToMasterServer()) { VERBOSE(VB_IMPORTANT, LOC_ERR + "Failed to connect to master server"); return GENERIC_EXIT_CONNECT_ERROR; } jobqueue = new JobQueue(false); MythSystemEventHandler *sysEventHandler = new MythSystemEventHandler(); int exitCode = a.exec(); if (sysEventHandler) delete sysEventHandler; return exitCode ? exitCode : GENERIC_EXIT_OK; }
Identity RecognitionDatabase::findIdentity(const QMap<QString, QString>& attributes) const { if (!d || !d->dbAvailable || attributes.isEmpty()) { return Identity(); } QMutexLocker lock(&d->mutex); Identity match; // First and foremost, UUID QString uuid = attributes.value(QString::fromLatin1("uuid")); match = d->findByAttribute(QString::fromLatin1("uuid"), uuid); if (!match.isNull()) { return match; } // A negative UUID match, with a given UUID, precludes any further search if (!uuid.isNull()) { return Identity(); } // full name match = d->findByAttributes(QString::fromLatin1("fullName"), attributes); if (!match.isNull()) { return match; } // name match = d->findByAttributes(QString::fromLatin1("name"), attributes); if (!match.isNull()) { return match; } QMap<QString, QString>::const_iterator it; for (it = attributes.begin(); it != attributes.end(); ++it) { if (it.key() == QString::fromLatin1("uuid") || it.key() == QString::fromLatin1("fullName") || it.key() == QString::fromLatin1("name")) { continue; } match = d->findByAttribute(it.key(), it.value()); if (!match.isNull()) { return match; } } return Identity(); }
void CallTipsList::showTips(const QString& line) { // search only once static QPixmap type_module_icon = BitmapFactory().pixmap("ClassBrowser/type_module.svg"); static QPixmap type_class_icon = BitmapFactory().pixmap("ClassBrowser/type_class.svg"); static QPixmap method_icon = BitmapFactory().pixmap("ClassBrowser/method.svg"); static QPixmap member_icon = BitmapFactory().pixmap("ClassBrowser/member.svg"); static QPixmap property_icon = BitmapFactory().pixmap("ClassBrowser/property.svg"); // object is in error state static const char * const forbidden_xpm[]={ "8 8 3 1", ". c None", "# c #ff0000", "a c #ffffff", "..####..", ".######.", "########", "#aaaaaa#", "#aaaaaa#", "########", ".######.", "..####.."}; static QPixmap forbidden_icon(forbidden_xpm); static QPixmap forbidden_type_module_icon = BitmapFactory().merge(type_module_icon,forbidden_icon,BitmapFactoryInst::BottomLeft); static QPixmap forbidden_type_class_icon = BitmapFactory().merge(type_class_icon,forbidden_icon,BitmapFactoryInst::BottomLeft); static QPixmap forbidden_method_icon = BitmapFactory().merge(method_icon,forbidden_icon,BitmapFactoryInst::BottomLeft); static QPixmap forbidden_member_icon = BitmapFactory().merge(member_icon,forbidden_icon,BitmapFactoryInst::BottomLeft); static QPixmap forbidden_property_icon = BitmapFactory().merge(property_icon,forbidden_icon,BitmapFactoryInst::BottomLeft); this->validObject = true; QString context = extractContext(line); QMap<QString, CallTip> tips = extractTips(context); clear(); for (QMap<QString, CallTip>::Iterator it = tips.begin(); it != tips.end(); ++it) { addItem(it.key()); QListWidgetItem *item = this->item(this->count()-1); item->setData(Qt::ToolTipRole, QVariant(it.value().description)); item->setData(Qt::UserRole, qVariantFromValue( it.value() )); //< store full CallTip data switch (it.value().type) { case CallTip::Module: { item->setIcon((this->validObject ? type_module_icon : forbidden_type_module_icon)); } break; case CallTip::Class: { item->setIcon((this->validObject ? type_class_icon : forbidden_type_class_icon)); } break; case CallTip::Method: { item->setIcon((this->validObject ? method_icon : forbidden_method_icon)); } break; case CallTip::Member: { item->setIcon((this->validObject ? member_icon : forbidden_member_icon)); } break; case CallTip::Property: { item->setIcon((this->validObject ? property_icon : forbidden_property_icon)); } break; default: break; } } if (count()==0) return; // nothing found // get the minimum width and height of the box int h = 0; int w = 0; for (int i = 0; i < count(); ++i) { QRect r = visualItemRect(item(i)); w = qMax(w, r.width()); h += r.height(); } // Add an offset w += 2*frameWidth(); h += 2*frameWidth(); // get the start position of the word prefix QTextCursor cursor = textEdit->textCursor(); this->cursorPos = cursor.position(); QRect rect = textEdit->cursorRect(cursor); int posX = rect.x(); int posY = rect.y(); int boxH = h; // Decide whether to show downstairs or upstairs if (posY > textEdit->viewport()->height()/2) { h = qMin(qMin(h,posY), 250); if (h < boxH) w += textEdit->style()->pixelMetric(QStyle::PM_ScrollBarExtent); setGeometry(posX,posY-h, w, h); } else { h = qMin(qMin(h,textEdit->viewport()->height()-fontMetrics().height()-posY), 250); if (h < boxH) w += textEdit->style()->pixelMetric(QStyle::PM_ScrollBarExtent); setGeometry(posX, posY+fontMetrics().height(), w, h); } setCurrentRow(0); show(); }
void medAbstractDatabaseImporter::importFile ( void ) { QMutexLocker locker ( &d->mutex ); /* The idea of this algorithm can be summarized in 3 steps: * 1. Get a list of all the files that will (try to) be imported or indexed * 2. Filter files that cannot be read, or won't be possible to write afterwards, or are already in the db * 3. Fill files metadata, write them to the db, and populate db tables * * note that depending on the input files, they might be aggregated by volume */ // 1) Obtain a list of all the files that are going to be processed // this flattens the tree structure (if the input is a directory) // and puts all the files in one single list QStringList fileList = getAllFilesToBeProcessed ( d->file ); // Files that pass the filters named above are grouped // by volume in this map and will be written in the db after. // the key will be the name of the aggregated file with the volume QMap<QString, QStringList> imagesGroupedByVolume; QMap<QString, QString> imagesGroupedByPatient; QMap<QString, QString> imagesGroupedBySeriesId; int currentFileNumber = 0; // this variable will be used only for calculating progress // if importing, and depending on the input files, they might be aggregated // that is: files corresponding to the same volume will be written // in a single output meta file (e.g. .mha) // this map is used to store a unique id per volume and its volume number QMap<QString, int> volumeUniqueIdToVolumeNumber; int volumeNumber = 1; // 2) Select (by filtering) files to be imported // // In this first loop we read the headers of all the images to be imported // and check if we don't have any problem in reading the file, the header // or in selecting a proper format to store the new file afterwards // new files ARE NOT written in medInria database yet, but are stored in a map for writing in a posterior step QString tmpPatientId; QString currentPatientId = ""; QString patientID; QString tmpSeriesUid; QString currentSeriesUid = "-1"; QString currentSeriesId = ""; bool atLeastOneImportSucceeded = false; foreach ( QString file, fileList ) { if ( d->isCancelled ) // check if user cancelled the process break; emit progress ( this, ( ( qreal ) currentFileNumber/ ( qreal ) fileList.count() ) * 50.0 ); //TODO: reading and filtering represents 50% of the importing process? currentFileNumber++; QFileInfo fileInfo ( file ); if (fileInfo.size() != 0) { dtkSmartPointer<medAbstractData> medData; // 2.1) Try reading file information, just the header not the whole file bool readOnlyImageInformation = true; medData = tryReadImages ( QStringList ( fileInfo.filePath() ), readOnlyImageInformation ); if ( !medData ) { qWarning() << "Reader was unable to read: " << fileInfo.filePath(); continue; } // 2.2) Fill missing metadata populateMissingMetadata ( medData, medMetaDataKeys::SeriesID.getFirstValue(medData)); QString patientName = medMetaDataKeys::PatientName.getFirstValue(medData).simplified(); QString birthDate = medMetaDataKeys::BirthDate.getFirstValue(medData); tmpPatientId = patientName + birthDate; if(tmpPatientId != currentPatientId) { currentPatientId = tmpPatientId; patientID = getPatientID(patientName, birthDate); } medData->setMetaData ( medMetaDataKeys::PatientID.key(), QStringList() << patientID ); tmpSeriesUid = medMetaDataKeys::SeriesDicomID.getFirstValue(medData); if (tmpSeriesUid != currentSeriesUid) { currentSeriesUid = tmpSeriesUid; currentSeriesId = medMetaDataKeys::SeriesID.getFirstValue(medData); } else medData->setMetaData ( medMetaDataKeys::SeriesID.key(), QStringList() << currentSeriesId ); // 2.3) Generate an unique id for each volume // all images of the same volume should share the same id QString volumeId = generateUniqueVolumeId ( medData ); // check whether the image belongs to a new volume if ( !volumeUniqueIdToVolumeNumber.contains ( volumeId ) ) { volumeUniqueIdToVolumeNumber[volumeId] = volumeNumber; volumeNumber++; } // 2.3) a) Determine future file name and path based on patient/study/series/image // i.e.: where we will write the imported image QString imageFileName = determineFutureImageFileName ( medData, volumeUniqueIdToVolumeNumber[volumeId] ); #ifdef Q_OS_WIN32 if ( (medStorage::dataLocation() + "/" + imageFileName).length() > 255 ) { emit showError ( tr ( "Your database path is too long" ), 5000 ); emit dataImported(medDataIndex(), d->uuid); emit failure ( this ); return; } #endif // 2.3) b) Find the proper extension according to the type of the data // i.e.: in which format we will write the file in our database QString futureExtension = determineFutureImageExtensionByDataType ( medData ); // we care whether we can write the image or not if we are importing if (!d->indexWithoutImporting && futureExtension.isEmpty()) { emit showError(tr("Could not save file due to unhandled data type: ") + medData->identifier(), 5000); continue; } imageFileName = imageFileName + futureExtension; // 2.3) c) Add the image to a map for writing them all in medInria's database in a posterior step // First check if patient/study/series/image path already exists in the database // Should we emit a message otherwise ??? TO if ( !checkIfExists ( medData, fileInfo.fileName() ) ) { imagesGroupedByVolume[imageFileName] << fileInfo.filePath(); imagesGroupedByPatient[imageFileName] = patientID; imagesGroupedBySeriesId[imageFileName] = currentSeriesId; } } else { QString error = QString(tr("Could not read empty file: ") + fileInfo.completeBaseName()); qWarning() << __FUNCTION__ << error; emit showError(error, 5000); } } // some checks to see if the user cancelled or something failed if ( d->isCancelled ) { emit showError (tr ( "User cancelled import process" ), 5000 ); emit dataImported(medDataIndex(), d->uuid); emit cancelled ( this ); return; } // from now on the process cannot be cancelled emit disableCancel ( this ); // 3) Re-read selected files and re-populate them with missing metadata // then write them to medInria db and populate db tables QMap<QString, QStringList>::const_iterator it = imagesGroupedByVolume.begin(); QMap<QString, QString>::const_iterator itPat = imagesGroupedByPatient.begin(); QMap<QString, QString>::const_iterator itSer = imagesGroupedBySeriesId.begin(); // 3.1) first check is after the filtering we have something to import // maybe we had problems with all the files, or they were already in the database if ( it == imagesGroupedByVolume.end() ) { // TODO we know if it's either one or the other error, we can make this error better... emit showError (tr ( "No compatible image found or all of them had been already imported." ), 5000 ); emit dataImported(medDataIndex(), d->uuid); emit failure ( this ); return; } else qDebug() << "Chosen directory contains " << imagesGroupedByVolume.size() << " files"; int imagesCount = imagesGroupedByVolume.count(); // used only to calculate progress int currentImageIndex = 0; // used only to calculate progress medDataIndex index; //stores the last volume's index to be emitted on success // final loop: re-read, re-populate and write to db for ( ; it != imagesGroupedByVolume.end(); it++ ) { emit progress ( this, ( ( qreal ) currentImageIndex/ ( qreal ) imagesCount ) * 50.0 + 50.0 ); // 50? I do not think that reading all the headers is half the job... currentImageIndex++; QString aggregatedFileName = it.key(); // note that this file might be aggregating more than one input files QStringList filesPaths = it.value(); // input files being aggregated, might be only one or many patientID = itPat.value(); QString seriesID = itSer.value(); //qDebug() << currentImageIndex << ": " << aggregatedFileName << "with " << filesPaths.size() << " files"; dtkSmartPointer<medAbstractData> imagemedData; QFileInfo imagefileInfo ( filesPaths[0] ); // 3.2) Try to read the whole image, not just the header bool readOnlyImageInformation = false; imagemedData = tryReadImages ( filesPaths, readOnlyImageInformation ); if ( imagemedData ) { // 3.3) a) re-populate missing metadata // if there is no SeriesDescription, we use the tag Series Instance UID (specific and required) populateMissingMetadata ( imagemedData, medMetaDataKeys::SeriesDicomID.getFirstValue(imagemedData)); imagemedData->setMetaData ( medMetaDataKeys::PatientID.key(), QStringList() << patientID ); imagemedData->setMetaData ( medMetaDataKeys::SeriesID.key(), QStringList() << seriesID ); // 3.3) b) now we are able to add some more metadata addAdditionalMetaData ( imagemedData, aggregatedFileName, filesPaths ); } else { qWarning() << "Could not repopulate data!"; emit showError (tr ( "Could not read data: " ) + filesPaths[0], 5000 ); emit dataImported(medDataIndex(), d->uuid); emit failure(this); return; } if ( !d->indexWithoutImporting ) { // create location to store file QFileInfo fileInfo ( medStorage::dataLocation() + aggregatedFileName ); if ( !fileInfo.dir().exists() && !medStorage::mkpath ( fileInfo.dir().path() ) ) { qDebug() << "Cannot create directory: " << fileInfo.dir().path(); continue; } // now writing file bool writeSuccess = tryWriteImage ( fileInfo.filePath(), imagemedData ); if ( !writeSuccess ) { emit showError (tr ( "Could not save data file: " ) + filesPaths[0], 5000 ); continue; } } atLeastOneImportSucceeded = true; // and finally we populate the database QFileInfo aggregatedFileNameFileInfo ( aggregatedFileName ); QString pathToStoreThumbnails = aggregatedFileNameFileInfo.dir().path() + "/" + aggregatedFileNameFileInfo.completeBaseName() + "/"; index = this->populateDatabaseAndGenerateThumbnails ( imagemedData, pathToStoreThumbnails ); if(!d->uuid.isNull()) { emit dataImported(index, d->uuid); } else { emit dataImported(index); } itPat++; itSer++; } // end of the final loop if ( ! atLeastOneImportSucceeded) { emit progress ( this,100 ); emit dataImported(medDataIndex(), d->uuid); emit failure(this); return; } d->index = index; emit progress ( this,100 ); emit success ( this ); }
QMap<QString, QString> proFileTagMap( const QString& text, QString currentPath ) { QString t = text; if (currentPath.isEmpty()) currentPath = QDir::currentPath(); QMap<QString, QString> tagMap; /* Strip any commments before we try to include. We still need to do it after we include to make sure the included file does not have comments */ t.replace( QRegExp(QLatin1String("#[^\n]*\n")), QLatin1String(" ") ); /* Strip comments, merge lines ending with backslash, add spaces around '=' and '+=', replace '\n' with ';', and simplify white spaces. */ t.replace( QRegExp(QLatin1String("#[^\n]*\n")), QLatin1String(" ") ); t.replace( QRegExp(QLatin1String("\\\\[^\n\\S]*\n")), QLatin1String(" ") ); t.replace( QLatin1String("="), QLatin1String(" = ") ); t.replace( QLatin1String("+ ="), QLatin1String(" += ") ); t.replace( QLatin1String("\n"), QLatin1String(";") ); t = t.simplified(); /* Populate tagMap with 'key = value' entries. */ QStringList lines = t.split(QLatin1Char(';')); QStringList::Iterator line; for ( line = lines.begin(); line != lines.end(); ++line ) { QStringList toks = (*line).split(QLatin1Char(' '), QString::SkipEmptyParts); if ( toks.count() >= 3 && (toks[1] == QLatin1String("=") || toks[1] == QLatin1String("+=") || toks[1] == QLatin1String("*=")) ) { QString tag = toks.first(); int k = tag.lastIndexOf( QLatin1Char(':') ); // as in 'unix:' if ( k != -1 ) tag = tag.mid( k + 1 ); toks.erase( toks.begin() ); QString action = toks.first(); toks.erase( toks.begin() ); if ( tagMap.contains(tag) ) { if ( action == QLatin1String("=") ) tagMap.insert( tag, toks.join(QLatin1String(" ")) ); else tagMap[tag] += QLatin1Char( ' ' ) + toks.join( QLatin1String(" ") ); } else { tagMap[tag] = toks.join( QLatin1String(" ") ); } } } /* Expand $$variables within the 'value' part of a 'key = value' pair. */ QRegExp var( QLatin1String("\\$\\$[({]?([a-zA-Z0-9_]+)[)}]?") ); QMap<QString, QString>::Iterator it; for ( it = tagMap.begin(); it != tagMap.end(); ++it ) { int i = 0; while ( (i = var.indexIn((*it), i)) != -1 ) { int len = var.matchedLength(); QString invocation = var.cap(1); QString after; if ( invocation == QLatin1String("system") ) { // skip system(); it will be handled in the next pass ++i; } else { if ( tagMap.contains(invocation) ) after = tagMap[invocation]; else if (invocation.toLower() == QLatin1String("pwd")) after = currentPath; (*it).replace( i, len, after ); i += after.length(); } } } /* Execute system() calls. */ QRegExp callToSystem( QLatin1String("\\$\\$system\\s*\\(([^()]*)\\)") ); for ( it = tagMap.begin(); it != tagMap.end(); ++it ) { int i = 0; while ( (i = callToSystem.indexIn((*it), i)) != -1 ) { /* This code is stolen from qmake's project.cpp file. Ideally we would use the same parser, so we wouldn't have this code duplication. */ QString after; char buff[256]; FILE *proc = QT_POPEN( callToSystem.cap(1).toLatin1().constData(), "r" ); while ( proc && !feof(proc) ) { int read_in = int(fread( buff, 1, 255, proc )); if ( !read_in ) break; for ( int i = 0; i < read_in; i++ ) { if ( buff[i] == '\n' || buff[i] == '\t' ) buff[i] = ' '; } buff[read_in] = '\0'; after += QLatin1String(buff); } (*it).replace( i, callToSystem.matchedLength(), after ); i += after.length(); } } return tagMap; }
// Make boundary blocks: //----------------------------------------------------------------------------- void SifGenerator::makeBoundaryBlocks() { int sifIndex = 0; int bcnum = 0; int diff = 0; QMap<int, int> boundaryBC; QMap<QString, int> boundaryList; /*(Boundary condition, edge) value pairs */ QList<QString> boundaryConditions; /* List of different boundary conditions */ QList<int> boundaryEdges; /* List of edges relating to some specific boundary condition */ QString tmp; boundaryBC.clear(); boundaryList.clear(); boundaryConditions.clear(); boundaryEdges.clear(); tmp.clear(); //Find the available boundary conditions for (int index = 0; index < boundaryConditionEditor.count(); index++) { DynamicEditor *bc = boundaryConditionEditor[index]; boundaryConditions.append(bc->nameEdit->text().trimmed()); } //Find the boundary conditions and edges related to them. for (int index = 0; index < boundaryConditions.count(); index++) { for(int k = 0; k < boundaryMap.count(); k++) { BoundaryPropertyEditor *bEdit = boundaryPropertyEditor[k]; if(bEdit->touched) { boundaryBC[index] = ++sifIndex; int originalIndex = boundaryMap.key(k); const QString bcname = bEdit->ui.boundaryConditionCombo->currentText().trimmed(); if (boundaryConditions.value(index) == bcname) boundaryList.insertMulti(bcname, originalIndex); } } } //qDebug() << "boundaryMap: " << boundaryMap; //qDebug() << "boundaryList: " << boundaryList; qDebug() << "boundaryConditions: " << boundaryConditions; //Arrange and sort boundary conditions for(int index = 0; index < boundaryConditions.count(); index++) { tmp.clear(); boundaryEdges.clear(); const QString name = boundaryConditions[index]; BoundaryPropertyEditor *bEdit = boundaryPropertyEditor[index]; DynamicEditor *bc = boundaryConditionEditor[index]; if(boundaryList.contains(name)) { bcnum++; te->append("Boundary Condition " + QString::number(bcnum)); if(boundaryConditions.count() > 1) { QMap <QString,int>::ConstIterator l = boundaryList.find(boundaryConditions[index]); while (l != boundaryList.end() && l.key()==boundaryConditions[index]){ boundaryEdges.append(l.value()); l++; } while ((l--) != boundaryList.begin() && l.key()==boundaryConditions[index]){ tmp.append(QString::number(l.value())); tmp.append(" "); } } if(boundaryConditions.count() <= 1) { QMap <QString,int>::ConstIterator l = boundaryList.begin(); while (l != boundaryList.end()) { boundaryEdges.append(l.value()); l++; } while ((l--) != boundaryList.begin()){ tmp.append(QString::number(l.value())); tmp.append(" "); } } te->append(" Target Boundaries(" + QString::number(boundaryEdges.count()) + ") = " + tmp); if ( bEdit->bodyProperties ) { te->append(" Body id = " + QString::number(bEdit->bodyID) ); } te->append(" Name = \"" + name + "\""); // check which one of the dynamic editors has "name" typed in nameEdit: for(int j = 0; j < boundaryConditionEditor.size(); j++) { DynamicEditor *bc = boundaryConditionEditor[j]; if(bc->menuAction != NULL) { if(bc->nameEdit->text().trimmed() == name && name != NULL) { // go through the hash of this dynamic editor: //-------------------------------------------- for(int i = 0; i < bc->hash.count(); i++) { hash_entry_t entry = bc->hash.values().at(i); QWidget *widget = entry.widget; QDomElement elem; if ( widget->isEnabled() ) { elem = entry.elem; if(elem.attribute("Widget", "") == "CheckBox") handleCheckBox(elem, widget); if(elem.attribute("Widget", "") == "Edit") handleBCLineEdit(elem, widget, boundaryBC); if(elem.attribute("Widget", "") == "Combo") handleComboBox(elem, widget); if(elem.attribute("Widget", "") == "TextEdit") handleTextEdit(elem, widget); } } } } } te->append("End\n"); } } }
int main(int argc, char *argv[]) { QMap<QString,ParamPair> paramList; QString username = ""; QString filename; QString printerName; bool haveUsername = FALSE; bool haveDatabaseURL = FALSE; bool loggedIn = FALSE; bool print = FALSE; bool printPreview = FALSE; bool close = FALSE; int numCopies = 1; // BVI::Sednacom // new options bool pdfOutput = FALSE; QString pdfFileName; // BVI::Sednacom QString databaseURL = ""; QString loadFromDB = ""; QApplication app(argc, argv); app.addLibraryPath("."); OpenRPT::languages.addTranslationToDefault(":/common.qm"); OpenRPT::languages.addTranslationToDefault(":/wrtembed.qm"); OpenRPT::languages.addTranslationToDefault(":/renderer.qm"); OpenRPT::languages.addTranslationToDefault(":/renderapp.qm"); OpenRPT::languages.installSelected(); if (app.argc() > 1) { haveUsername = FALSE; bool havePasswd = FALSE; QString passwd = ""; QStringList arguments; QString firstArgument = QString( app.argv()[ 1 ] ); if( firstArgument.startsWith("-fromStdin=", Qt::CaseInsensitive) ){ QFile file; file.open(stdin, QIODevice::ReadOnly); QTextStream in(&file); in.setCodec( firstArgument.right( firstArgument.length() - 11 ).toAscii() ); QString arg; while( arg.compare("-launch") !=0 ){ arg = in.readLine(); arguments << arg; } file.close(); } else{ for (int intCounter = 1; intCounter < app.argc(); intCounter++){ arguments << QString (app.argv()[intCounter]); } } for ( QStringList::Iterator it = arguments.begin(); it != arguments.end(); ++it ) { QString argument( *it ); if (argument.startsWith("-databaseURL=", Qt::CaseInsensitive)) { haveDatabaseURL = TRUE; databaseURL = argument.right(argument.length() - 13); } else if (argument.startsWith("-username="******"-passwd=", Qt::CaseInsensitive)) { havePasswd = TRUE; passwd = argument.right(argument.length() - 8); } else if (argument.toLower() == "-noauth") { haveUsername = TRUE; havePasswd = TRUE; } else if (argument.startsWith("-numCopies=", Qt::CaseInsensitive)){ numCopies = argument.right( argument.length() - 11).toInt(); } else if (argument.toLower() == "-print") print = true; else if (argument.toLower() == "-printpreview") printPreview = true; else if (argument.toLower() == "-close") close = true; else if (argument.startsWith("-printerName=", Qt::CaseInsensitive)) printerName = argument.right(argument.length() - 13); else if (argument.startsWith("-param=", Qt::CaseInsensitive)) { QString str = argument.right(argument.length() - 7); bool active = true; QString name; QString type; QString value; QVariant var; int sep = str.indexOf('='); if(sep == -1) name = str; else { name = str.left(sep); value = str.right(str.length() - (sep + 1)); } str = name; sep = str.indexOf(':'); if(sep != -1) { name = str.left(sep); type = str.right(str.length() - (sep + 1)); } if(name.startsWith("-")) { name = name.right(name.length() - 1); active = false; } else if(name.startsWith("+")) name = name.right(name.length() - 1); if(!value.isEmpty()) var = XVariant::decode(type, value); paramList[name] = ParamPair(active, var); } // BVI::Sednacom // manage new arguments for CLI else if (argument.startsWith("-pdf", Qt::CaseInsensitive)) { pdfOutput = true ; } else if (argument.startsWith("-outpdf=", Qt::CaseInsensitive)) { pdfFileName = argument.right(argument.length() - 8 ) ; } // BVI::Sednacom else if (argument.startsWith("-loadfromdb=", Qt::CaseInsensitive)) loadFromDB = argument.right(argument.length() - 12); else if (argument.toLower() == "-e") XSqlQuery::setNameErrorValue("Missing"); else if(!argument.startsWith("-")) filename = argument; } if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) ) { QSqlDatabase db; QString protocol; QString hostName; QString dbName; QString port; db = databaseFromURL( databaseURL ); if (!db.isValid()) { QMessageBox::critical(0, QObject::tr("Can not load database driver"), QObject::tr("Unable to load the database driver. Please contact your systems administrator.")); QApplication::exit(-1); } db.setUserName(username); db.setPassword(passwd); if (!db.open()) { QMessageBox::critical(0, QObject::tr("Unable to connect to database"), QObject::tr("Unable to connect to the database with the given information.")); QApplication::exit(-1); } else loggedIn = TRUE; } } if(!loggedIn) { ParameterList params; params.append("name", RenderWindow::name()); params.append("copyright", OpenRPT::copyright); params.append("version", OpenRPT::version); params.append("build", OpenRPT::build); if (haveUsername) params.append("username", username); if (haveDatabaseURL) params.append("databaseURL", databaseURL); login newdlg(0, "", TRUE); newdlg.set(params, 0); if (newdlg.exec() == QDialog::Rejected) return -1; } RenderWindow mainwin; mainwin._printerName = printerName; if(!filename.isEmpty()) mainwin.fileOpen(filename); if(!loadFromDB.isEmpty()) mainwin.fileLoad(loadFromDB); QMap<QString,ParamPair>::Iterator it; for ( it = paramList.begin(); it != paramList.end(); ++it ) { mainwin.updateParam(it.key(), it.value().second, it.value().first); } // BVI::Sednacom // do not display window for PDF output if (!pdfOutput) mainwin.show(); // BVI::Sednacom if(print) mainwin.filePrint( numCopies ); if(printPreview) mainwin.filePreview( numCopies ); // BVI::Sednacom // generate the PDF if (pdfOutput) mainwin.filePrintToPDF(pdfFileName); // BVI::Sednacom if(close) { mainwin.fileExit(); return 0; } return app.exec(); }
DTC::EncoderList* Dvr::GetEncoderList() { DTC::EncoderList* pList = new DTC::EncoderList(); QList<InputInfo> inputInfoList = CardUtil::GetAllInputInfo(); QMap<int, EncoderLink *>::Iterator iter = tvList.begin(); for (; iter != tvList.end(); ++iter) { EncoderLink *elink = *iter; if (elink != NULL) { DTC::Encoder *pEncoder = pList->AddNewEncoder(); pEncoder->setId ( elink->GetCardID() ); pEncoder->setState ( elink->GetState() ); pEncoder->setLocal ( elink->IsLocal() ); pEncoder->setConnected ( elink->IsConnected() ); pEncoder->setSleepStatus ( elink->GetSleepStatus() ); // pEncoder->setLowOnFreeSpace( elink->isLowOnFreeSpace()); if (pEncoder->Local()) pEncoder->setHostName( gCoreContext->GetHostName() ); else pEncoder->setHostName( elink->GetHostName() ); QList<InputInfo>::iterator it = inputInfoList.begin(); for (; it < inputInfoList.end(); ++it) { InputInfo inputInfo = *it; if (inputInfo.cardid == static_cast<uint>(elink->GetCardID())) { DTC::Input *input = pEncoder->AddNewInput(); FillInputInfo(input, inputInfo); } } switch ( pEncoder->State() ) { case kState_WatchingLiveTV: case kState_RecordingOnly: case kState_WatchingRecording: { ProgramInfo *pInfo = elink->GetRecording(); if (pInfo) { DTC::Program *pProgram = pEncoder->Recording(); FillProgramInfo( pProgram, pInfo, true, true ); delete pInfo; } break; } default: break; } } } return pList; }
/** * \brief This function verify if a similar element is not already written and write the element at the good place * \author Jules Gorny - ALCoV team, ISIT, UMR 6284 UdA – CNRS * \param doc : QDomDocument containing the xml tree * \param elemName : Name of the XML element * \param elemValue : Value of the XML element * \param attributes : QMap<QString, QString> with the attribute's name in key and the atttribute's value in value * \param parentsStr : A string containing a hierarchy of parents written like .../.../grandFather/father (used to compare the parents of existing elements and the new one) * \param parentsAttr : QMap<QString, QMap<QString, QString>> containing the parent name in the key and a map build like the attributes param in the value (used to compare the parents of existing elements and the new one) * \param ui : in case we want to write a message to the user. **/ void writeElement(QDomDocument &doc, QDomElement &addedNode, QString elemName, QString elemValue, QMap<QString, QString> attributes, QString parentsStr, QMap<QString, QMap<QString, QString>> parentsAttr, Ui::MainWindow *ui) { QStringList parents; if(parentsStr != "") parents = parentsStr.split("/"); /** * We try to find where we want to include our new node. For that we browse the XML tree keeping a track on the closer parent of our node we found. * This closer parent is named "last parent" cause it's the last we found while going deeper in the tree. **/ QDomNodeList lastParentFoundList; QDomNode ourActualLastParent; //If we have at least one parent, we search the first one (it will be "Patient") if( parents.size() > 0 ) { lastParentFoundList = doc.elementsByTagName(parents.at(0)); ourActualLastParent = lastParentFoundList.at(0); } //If we don't have parents else { //And if there is no Patient node if( doc.elementsByTagName("Patient").size() == 0 ) { //We create the element at the root (if the program is well written, it's supposed to be a new Patient node) addedNode = doc.createElement(elemName); if( elemValue != "" ) { QDomText nameText = doc.createTextNode(elemValue); addedNode.appendChild(nameText); } if( attributes.size() > 0 ) { QMap<QString, QString>::Iterator it; for( it = attributes.begin() ; it != attributes.end() ; ++it) addedNode.setAttribute(it.key(), it.value()); } doc.appendChild(addedNode); } } //The lastParent is now initialized with "Patient", we can browse the rest of the parents tree. for( int p=1; p<parents.size(); p++ ) { //We search the list of nodes corresponding to second older parent name (after Patient) lastParentFoundList = ourActualLastParent.toElement().elementsByTagName(parents.at(p)); //If we can't find any parent candidate, there is a problem in the program ... if( lastParentFoundList.size() == 0 ) { addProgressMessage(ui, "Looks like the developper didn't do a great job. The parents list doesn't match the XML file we are browsing.", Qt::black, "", false); } //If there is at least one parent node found with that name, we will compare the attribute else { bool weFoundWhatWeWanted = false; //Browse the different parent candidates for( int f=0; f<lastParentFoundList.size(); f++ ) { //We estimate that the attributes correspond to what we want bool areAllAttributesSimilar = true; QDomNamedNodeMap parentsAttributes = lastParentFoundList.at(f).attributes(); //We browse the attribute to find if one attribute doesn't correspond for(int a=0; a<parentsAttributes.size(); a++) { QString parentAttrName = parentsAttributes.item(a).toAttr().name(); QString parentAttrValue = parentsAttributes.item(a).toAttr().value(); QMap<QString, QString> tempAttr = parentsAttr.find(parents.at(p)).value(); //In that case, we continue to browse the different parent candidates if( !tempAttr.contains(parentAttrName) || tempAttr.find(parentAttrName).value() != parentAttrValue) { areAllAttributesSimilar = false; break; } } //If we found the perfect candidate, we keep it and stop brownsing the candidates. We can go deeper in the tree. if( areAllAttributesSimilar ) { ourActualLastParent = lastParentFoundList.at(f); weFoundWhatWeWanted = true; break; } } //If we didn't find any corresponding parent, there is a problem in the program ... if( !weFoundWhatWeWanted ) { addProgressMessage(ui, "Looks like the developper didn't do a great job. The parents list doesn't match the XML file we are browsing.", Qt::black, "", false); } } } //We finally found our closer parent ! QDomNodeList sameElementFoundList; sameElementFoundList = ourActualLastParent.toElement().elementsByTagName(elemName); bool isAnElementSimilar = false; //We try to find a similar element (Name + attributes) for( int f=0; f<sameElementFoundList.size(); f++ ) { bool areAllAttributesSimilar = true; QDomNamedNodeMap parentsAttributes = sameElementFoundList.at(f).attributes(); for(int a=0; a<parentsAttributes.size(); a++) { QString parentAttrName = parentsAttributes.item(a).toAttr().name(); QString parentAttrValue = parentsAttributes.item(a).toAttr().value(); if( !attributes.contains(parentAttrName) || attributes.find(parentAttrName).value() != parentAttrValue) { areAllAttributesSimilar = false; break; } } if( areAllAttributesSimilar ) { isAnElementSimilar = true; addedNode = sameElementFoundList.at(f).toElement(); break; } } //If the element definitly doesn't exists, we create it if( !isAnElementSimilar ) { addedNode = doc.createElement(elemName); if( elemValue != "" ) { QDomText nameText = doc.createTextNode(elemValue); addedNode.appendChild(nameText); } if( attributes.size() > 0 ) { QMap<QString, QString>::Iterator it; for( it = attributes.begin() ; it != attributes.end() ; ++it) addedNode.setAttribute(it.key(), it.value()); } ourActualLastParent.toElement().appendChild(addedNode); } }
void PatchRoadGenerator::generateRoadNetwork() { srand(12345); // mark all the existing vertices as fixed { RoadVertexIter vi, vend; for (boost::tie(vi, vend) = boost::vertices(roads.graph); vi != vend; ++vi) { roads.graph[*vi]->fixed = true; } } // remove all the local streets temporalily QMap<RoadEdgeDesc, bool> originalLocalStreets; { RoadEdgeIter ei, eend; for (boost::tie(ei, eend) = boost::edges(roads.graph); ei != eend; ++ei) { if (!roads.graph[*ei]->valid) continue; if (roads.graph[*ei]->type == RoadEdge::TYPE_STREET) { originalLocalStreets[*ei] = true; roads.graph[*ei]->valid = false; } } } std::list<RoadVertexDesc> seeds; // Avenueのシードを生成 generateAvenueSeeds(seeds); // Avenueを生成 std::cout << "Avenue generation started." << std::endl; { // detect interesting shapes std::vector<std::vector<RoadEdgeDescs> > shapes; std::vector<std::vector<Patch> > patches; { shapes.resize(features.size()); patches.resize(features.size()); for (int i = 0; i < features.size(); ++i) { shapes[i] = features[i].shapes(RoadEdge::TYPE_AVENUE, G::getFloat("houghScale"), G::getFloat("avenuePatchDistance")); patches[i] = RoadGeneratorHelper::convertToPatch(RoadEdge::TYPE_AVENUE, features[i].roads(RoadEdge::TYPE_AVENUE), features[i].roads(RoadEdge::TYPE_AVENUE), shapes[i]); } } int iter; for (iter = 0; !seeds.empty() && iter < G::getInt("numAvenueIterations"); ) { RoadVertexDesc desc = seeds.front(); seeds.pop_front(); // 既に3つ以上エッジがある場合は、スキップする if (GraphUtil::getDegree(roads, desc) >= 3) { continue; } // エリアの外なら、スキップする if (!targetArea.contains(roads.graph[desc]->pt)) { printf("ERROR: this check should have been done before.\n"); continue; } // 水中なら、スキップする float z = vboRenderManager->getTerrainHeight(roads.graph[desc]->pt.x(), roads.graph[desc]->pt.y(), true); if (z < G::getFloat("seaLevelForAvenue")) { std::cout << "attemptExpansion (avenue): " << iter << " (skipped because it is under the sea)" << std::endl; continue; } std::cout << "attemptExpansion (avenue): " << iter << " (Seed: " << desc << ")" << std::endl; //int ex_id = roads.graph[desc]->properties["ex_id"].toInt(); int ex_id = defineExId(roads.graph[desc]->pt); if (!attemptConnect(RoadEdge::TYPE_AVENUE, desc, ex_id, features, seeds)) { if (!attemptExpansion(RoadEdge::TYPE_AVENUE, desc, ex_id, features[ex_id], patches[ex_id], seeds)) { attemptExpansion2(RoadEdge::TYPE_AVENUE, desc, features[ex_id], seeds); } } char filename[255]; sprintf(filename, "road_images/avenues_%d.jpg", iter); RoadGeneratorHelper::saveRoadImage(roads, seeds, filename); iter++; } } std::cout << "Avenue generation completed." << std::endl; seeds.clear(); // Avenueをクリーンナップ if (G::getBool("cleanAvenues")) { removeDeadend(roads); } if (G::getBool("removeSmallBlocks")) { SmallBlockRemover::remove(roads, G::getFloat("minBlockSize")); } // recover the temporarily removed local streets if they are not intersected with other edges { for (QMap<RoadEdgeDesc, bool>::iterator it = originalLocalStreets.begin(); it != originalLocalStreets.end(); ++it) { if (!GraphUtil::isIntersect(roads, roads.graph[it.key()]->polyline)) { roads.graph[it.key()]->valid = true; } } } // Local streetを生成 if (G::getBool("generateLocalStreets")) { generateStreetSeeds(seeds); // detect interesting shapes std::vector<std::vector<RoadEdgeDescs> > shapes; std::vector<std::vector<Patch> > patches; { shapes.resize(features.size()); patches.resize(features.size()); for (int i = 0; i < features.size(); ++i) { shapes[i] = features[i].shapes(RoadEdge::TYPE_STREET, G::getFloat("houghScale") * 0.2f, G::getFloat("streetPatchDistance")); patches[i] = RoadGeneratorHelper::convertToPatch(RoadEdge::TYPE_STREET, features[i].roads(RoadEdge::TYPE_STREET), features[i].roads(RoadEdge::TYPE_AVENUE), shapes[i]); } } std::cout << "Local street generation started." << std::endl; int iter; for (iter = 0; !seeds.empty() && iter < G::getInt("numStreetIterations");) { RoadVertexDesc desc = seeds.front(); seeds.pop_front(); // 既に3つ以上エッジがある場合は、スキップする if (GraphUtil::getDegree(roads, desc) >= 3) { continue; } // エリアの外なら、スキップする if (!targetArea.contains(roads.graph[desc]->pt)) { printf("ERROR: this check should have been done before.\n"); continue; } float z = vboRenderManager->getTerrainHeight(roads.graph[desc]->pt.x(), roads.graph[desc]->pt.y(), true); if (z < G::getFloat("seaLevelForStreet")) { std::cout << "attemptExpansion (street): " << iter << " (skipped because it is under the sea or on the mountains)" << std::endl; continue; } std::cout << "attemptExpansion (street): " << iter << " (Seed: " << desc << ")" << std::endl; int ex_id = roads.graph[desc]->properties["ex_id"].toInt(); //if (!attemptConnect(RoadEdge::TYPE_STREET, desc, features[ex_id], seeds)) { if (!attemptExpansion(RoadEdge::TYPE_STREET, desc, ex_id, features[ex_id], patches[ex_id], seeds)) { attemptExpansion2(RoadEdge::TYPE_STREET, desc, features[ex_id], seeds); } //} char filename[255]; sprintf(filename, "road_images/streets_%d.jpg", iter); RoadGeneratorHelper::saveRoadImage(roads, seeds, filename); iter++; } std::cout << "Local street generation completed." << std::endl; } // 指定されたエリアでCropping if (G::getBool("cropping")) { GraphUtil::extractRoads2(roads, targetArea); } if (G::getBool("cleanStreets")) { RoadGeneratorHelper::removeDeadend(roads); } GraphUtil::cleanEdges(roads); }
void CImporter::_createAnimations() { aiAnimation* anim = null; for (uint i = 0; i < m_scene->mNumAnimations; i++) { if (!anim) anim = m_scene->mAnimations[i]; else { if (m_scene->mAnimations[i]->mDuration > anim->mDuration) anim = m_scene->mAnimations[i]; } } if (!anim || !anim->mNumChannels) return; if (anim->mTicksPerSecond != 0.0) m_ticksPerSecond = anim->mTicksPerSecond; else m_ticksPerSecond = 1.0; m_frameCount = (int)((anim->mDuration / m_ticksPerSecond) * 30.0 + 1.5); if (!m_frameCount) return; QMap<int, TMAnimation*> bonesAni; bool found; aiNodeAnim* nodeAnim = null; int j; for (uint i = 0; i < anim->mNumChannels; i++) { nodeAnim = anim->mChannels[i]; TMAnimation* frames = _createAnimation(nodeAnim); const string name(string(nodeAnim->mNodeName.C_Str())); auto it = m_mapObjects.find(string(nodeAnim->mNodeName.C_Str())); if (it != m_mapObjects.end()) { it.value()->frames = frames; m_obj3D->m_frameCount = m_frameCount; continue; } found = false; if (m_useBones) { for (j = 0; j < m_boneNodes.size(); j++) { if (name == m_bones[j].name) { bonesAni[j] = frames; found = true; break; } } } if (!found) DeleteArray(frames); } m_mesh->m_frameCount = m_frameCount; if (bonesAni.size() > 0) { CMotion* motion = new CMotion(); motion->m_ID = _getNewID(); motion->m_boneCount = m_boneNodes.size(); motion->m_bones = m_bones; motion->m_frameCount = m_frameCount; motion->m_attributes = new MotionAttribute[motion->m_frameCount]; memset(motion->m_attributes, 0, sizeof(MotionAttribute) * motion->m_frameCount); motion->m_animations = new TMAnimation[bonesAni.size() * m_frameCount]; memset(motion->m_animations, 0, sizeof(TMAnimation) * bonesAni.size() * m_frameCount); motion->m_frames = new BoneFrame[motion->m_boneCount]; memset(motion->m_frames, 0, sizeof(BoneFrame) * motion->m_boneCount); TMAnimation* frames = motion->m_animations; for (int i = 0; i < motion->m_boneCount; i++) { if (bonesAni.find(i) != bonesAni.end()) { motion->m_frames[i].frames = frames; memcpy(frames, bonesAni[i], sizeof(TMAnimation) * m_frameCount); frames += m_frameCount; } else { motion->m_frames[i].frames = null; motion->m_frames[i].TM = m_bones[i].localTM; } } if (m_externBones) { m_mesh->m_motion = motion; m_mesh->m_skeleton->m_bones = new Bone[m_mesh->m_skeleton->m_boneCount]; memcpy(m_mesh->m_skeleton->m_bones, m_bones, sizeof(Bone) * m_mesh->m_skeleton->m_boneCount); } else { m_obj3D->m_motion = motion; m_obj3D->m_frameCount = m_frameCount; } } if (bonesAni.size() > 0) { for (auto it = bonesAni.begin(); it != bonesAni.end(); it++) DeleteArray(it.value()); } if (m_obj3D->m_frameCount) { m_obj3D->m_attributes = new MotionAttribute[m_obj3D->m_frameCount]; memset(m_obj3D->m_attributes, 0, sizeof(MotionAttribute) * m_obj3D->m_frameCount); } }