void DatabaseTabWidget::openDatabase(const QString& fileName, const QString& pw, const QString& keyFile) { QFileInfo fileInfo(fileName); QString canonicalFilePath = fileInfo.canonicalFilePath(); if (canonicalFilePath.isEmpty()) { MessageBox::warning(this, tr("Warning"), tr("File not found!")); return; } QHashIterator<Database*, DatabaseManagerStruct> i(m_dbList); while (i.hasNext()) { i.next(); if (i.value().canonicalFilePath == canonicalFilePath) { setCurrentIndex(databaseIndex(i.key())); return; } } DatabaseManagerStruct dbStruct; // test if we can read/write or read the file QFile file(fileName); // TODO: error handling if (!file.open(QIODevice::ReadWrite)) { if (!file.open(QIODevice::ReadOnly)) { // can't open // TODO: error message return; } else { // can only open read-only dbStruct.readOnly = true; } } file.close(); QLockFile* lockFile = new QLockFile(QString("%1/.%2.lock").arg(fileInfo.canonicalPath(), fileInfo.fileName())); lockFile->setStaleLockTime(0); if (!dbStruct.readOnly && !lockFile->tryLock()) { // for now silently ignore if we can't create a lock file // due to lack of permissions if (lockFile->error() != QLockFile::PermissionError) { QMessageBox::StandardButton result = MessageBox::question(this, tr("Open database"), tr("The database you are trying to open is locked by another instance of KeePassX.\n" "Do you want to open it anyway? Alternatively the database is opened read-only."), QMessageBox::Yes | QMessageBox::No); if (result == QMessageBox::No) { dbStruct.readOnly = true; delete lockFile; lockFile = nullptr; } else { // take over the lock file if possible if (lockFile->removeStaleLockFile()) { lockFile->tryLock(); } } } } Database* db = new Database(); dbStruct.dbWidget = new DatabaseWidget(db, this); dbStruct.lockFile = lockFile; dbStruct.saveToFilename = !dbStruct.readOnly; dbStruct.filePath = fileInfo.absoluteFilePath(); dbStruct.canonicalFilePath = canonicalFilePath; dbStruct.fileName = fileInfo.fileName(); insertDatabase(db, dbStruct); updateLastDatabases(dbStruct.filePath); if (!pw.isNull() || !keyFile.isEmpty()) { dbStruct.dbWidget->switchToOpenDatabase(dbStruct.filePath, pw, keyFile); } else { dbStruct.dbWidget->switchToOpenDatabase(dbStruct.filePath); } }
bool KStreamSocket::connect(const QString& node, const QString& service) { if (state() == Connected) return true; // already connected if (state() > Connected) return false; // can't do much here if (!node.isNull()) peerResolver().setNodeName(node); if (!service.isNull()) peerResolver().setServiceName(service); if (state() == Connecting && !blocking()) { setError(IO_ConnectError, InProgress); emit gotError(InProgress); return true; // we're already connecting } if (state() < HostFound) { // connection hasn't started yet if (!blocking()) { QObject::connect(this, SIGNAL(hostFound()), SLOT(hostFoundSlot())); return lookup(); } // blocking mode if (!lookup()) return false; // lookup failure } /* * lookup results are available here */ if (timeout() > 0) { if (!blocking() && !d->timer.isActive()) d->timer.start(timeout(), true); else { // blocking connection with timeout // this must be handled as a special case because it requires a // non-blocking socket d->timer.stop(); // no need for a timer here socketDevice()->setBlocking(false); while (true) { connectionEvent(); if (state() < Connecting) return false; // error connecting if (state() == Connected) return true; // connected! if (remainingTimeout() <= 0) { // we've timed out timeoutSlot(); return false; } if (socketDevice()->error() == InProgress) { bool timedout; socketDevice()->poll(remainingTimeout(), &timedout); if (timedout) { timeoutSlot(); return false; } } } } } connectionEvent(); return error() == NoError; }
QString qmake_getpwd() { if(pwd.isNull()) pwd = QDir::currentPath(); return pwd; }
int runQMake(int argc, char **argv) { // stderr is unbuffered by default, but stdout buffering depends on whether // there is a terminal attached. Buffering can make output from stderr and stdout // appear out of sync, so force stdout to be unbuffered as well. // This is particularly important for things like QtCreator and scripted builds. setvbuf(stdout, (char *)NULL, _IONBF, 0); // parse command line int ret = Option::init(argc, argv); if(ret != Option::QMAKE_CMDLINE_SUCCESS) { if ((ret & Option::QMAKE_CMDLINE_ERROR) != 0) return 1; return 0; } QString oldpwd = qmake_getpwd(); #ifdef Q_WS_WIN if(!(oldpwd.length() == 3 && oldpwd[0].isLetter() && oldpwd.endsWith(":/"))) #endif { if(oldpwd.right(1) != QString(QChar(QDir::separator()))) oldpwd += QDir::separator(); } Option::output_dir = oldpwd; //for now this is the output dir if(Option::output.fileName() != "-") { QFileInfo fi(Option::output); QString dir; if(fi.isDir()) { dir = fi.filePath(); } else { QString tmp_dir = fi.path(); if(!tmp_dir.isEmpty() && QFile::exists(tmp_dir)) dir = tmp_dir; } if(!dir.isNull() && dir != ".") Option::output_dir = dir; if(QDir::isRelativePath(Option::output_dir)) Option::output_dir.prepend(oldpwd); Option::output_dir = QDir::cleanPath(Option::output_dir); } QMakeProperty prop; if(Option::qmake_mode == Option::QMAKE_QUERY_PROPERTY || Option::qmake_mode == Option::QMAKE_SET_PROPERTY) return prop.exec() ? 0 : 101; QMakeProject project(&prop); int exit_val = 0; QStringList files; if(Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT) files << "(*hack*)"; //we don't even use files, but we do the for() body once else files = Option::mkfile::project_files; for(QStringList::Iterator pfile = files.begin(); pfile != files.end(); pfile++) { if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE || Option::qmake_mode == Option::QMAKE_GENERATE_PRL) { QString fn = Option::fixPathToLocalOS((*pfile)); if(!QFile::exists(fn)) { fprintf(stderr, "Cannot find file: %s.\n", fn.toLatin1().constData()); exit_val = 2; continue; } //setup pwd properly debug_msg(1, "Resetting dir to: %s", oldpwd.toLatin1().constData()); qmake_setpwd(oldpwd); //reset the old pwd int di = fn.lastIndexOf(QDir::separator()); if(di != -1) { debug_msg(1, "Changing dir to: %s", fn.left(di).toLatin1().constData()); if(!qmake_setpwd(fn.left(di))) fprintf(stderr, "Cannot find directory: %s\n", fn.left(di).toLatin1().constData()); fn = fn.right(fn.length() - di - 1); } // read project.. if(!project.read(fn)) { fprintf(stderr, "Error processing project file: %s\n", fn == "-" ? "(stdin)" : (*pfile).toLatin1().constData()); exit_val = 3; continue; } if(Option::mkfile::do_preprocess) //no need to create makefile continue; } bool success = true; MetaMakefileGenerator *mkfile = MetaMakefileGenerator::createMetaGenerator(&project, QString(), false, &success); if (!success) exit_val = 3; if(mkfile && !mkfile->write(oldpwd)) { if(Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT) fprintf(stderr, "Unable to generate project file.\n"); else fprintf(stderr, "Unable to generate makefile for: %s\n", (*pfile).toLatin1().constData()); exit_val = 5; } delete mkfile; mkfile = NULL; } qmakeClearCaches(); return exit_val; }
PackageWindow::PackageWindow( Package *package, const QString &server ) : QWidget( 0, 0, 0 ) { QString str; if ( package ) { Package *local = package->getLocalPackage(); setCaption( package->getPackageName() ); QString destName; if ( local ) { if ( local->getInstalledTo() ) destName = package->getLocalPackage()->getInstalledTo()->getDestinationName(); } else { if ( package->getInstalledTo() ) destName = package->getInstalledTo()->getDestinationName(); } if ( !package->isPackageStoredLocally() ) { str.append( tr( "<b>Description</b> - " ) ); str.append( package->getDescription() ); if ( !destName.isNull() ) { str.append( tr( "<p><b>Installed To</b> - " ) ); str.append( destName ); } str.append( tr( "<p><b>Size</b> - " ) ); str.append( package->getPackageSize() ); str.append( tr( "<p><b>Section</b> - " ) ); str.append( package->getSection() ); } else { str.append( tr( "<p><b>Filename</b> - " ) ); str.append( package->getFilename() ); } if ( server == LOCAL_SERVER ) { str.append( tr( "<p><b>Version Installed</b> - " ) ); str.append( package->getVersion() ); } else { str.append( tr( "<p><b>Version Available</b> - " ) ); str.append( package->getVersion() ); if ( local ) { if ( package->isInstalled() ) { str.append( tr( "<p><b>Version Installed</b> - " ) ); str.append( package->getInstalledVersion() ); } } } } else { setCaption( tr( "Package Information" ) ); str = tr( "Package information is unavailable" ); } QVBoxLayout *layout = new QVBoxLayout( this, 4, 4 ); QTextView *l = new QTextView( str, QString::null, this ); layout->addWidget( l ); QPushButton *btn = new QPushButton( Opie::Core::OResource::loadPixmap( "enter", Opie::Core::OResource::SmallIcon ), tr( "Close" ), this ); layout->addWidget( btn ); connect( btn, SIGNAL( clicked() ), this, SLOT( close() ) ); }
void RS_Font::readCXF(QString path) { QString line; QFile f(path); f.open(QIODevice::ReadOnly); QTextStream ts(&f); // Read line by line until we find a new letter: while (!ts.atEnd()) { line = ts.readLine(); if (line.isEmpty()) continue; // Read font settings: if (line.at(0)=='#') { QStringList lst = ( line.right(line.length()-1) ).split(':', QString::SkipEmptyParts); QStringList::Iterator it3 = lst.begin(); // RVT_PORT sometimes it happens that the size is < 2 if (lst.size()<2) continue; QString identifier = (*it3).trimmed(); it3++; QString value = (*it3).trimmed(); if (identifier.toLower()=="letterspacing") { letterSpacing = value.toDouble(); } else if (identifier.toLower()=="wordspacing") { wordSpacing = value.toDouble(); } else if (identifier.toLower()=="linespacingfactor") { lineSpacingFactor = value.toDouble(); } else if (identifier.toLower()=="author") { authors.append(value); } else if (identifier.toLower()=="name") { names.append(value); } else if (identifier.toLower()=="encoding") { ts.setCodec(QTextCodec::codecForName(value.toLatin1())); encoding = value; } } // Add another letter to this font: else if (line.at(0)=='[') { // uniode character: QChar ch; // read unicode: QRegExp regexp("[0-9A-Fa-f]{4,4}"); regexp.indexIn(line); QString cap = regexp.cap(); if (!cap.isNull()) { int uCode = cap.toInt(NULL, 16); ch = QChar(uCode); } // read UTF8 (LibreCAD 1 compatibility) else if (line.indexOf(']')>=3) { int i = line.indexOf(']'); QString mid = line.mid(1, i-1); ch = QString::fromUtf8(mid.toLatin1()).at(0); } // read normal ascii character: else { ch = line.at(1); } // create new letter: RS_FontChar* letter = new RS_FontChar(NULL, ch, RS_Vector(0.0, 0.0)); // Read entities of this letter: QString coordsStr; QStringList coords; QStringList::Iterator it2; do { line = ts.readLine(); if (line.isEmpty()) { continue; } coordsStr = line.right(line.length()-2); // coords = QStringList::split(',', coordsStr); coords = coordsStr.split(',', QString::SkipEmptyParts); it2 = coords.begin(); // Line: if (line.at(0)=='L') { double x1 = (*it2++).toDouble(); double y1 = (*it2++).toDouble(); double x2 = (*it2++).toDouble(); double y2 = (*it2).toDouble(); RS_LineData ld(RS_Vector(x1, y1), RS_Vector(x2, y2)); RS_Line* line = new RS_Line(letter, ld); line->setPen(RS_Pen(RS2::FlagInvalid)); line->setLayer(NULL); letter->addEntity(line); } // Arc: else if (line.at(0)=='A') { double cx = (*it2++).toDouble(); double cy = (*it2++).toDouble(); double r = (*it2++).toDouble(); double a1 = (*it2++).toDouble()/ARAD; double a2 = (*it2).toDouble()/ARAD; bool reversed = (line.at(1)=='R'); RS_ArcData ad(RS_Vector(cx,cy), r, a1, a2, reversed); RS_Arc* arc = new RS_Arc(letter, ad); arc->setPen(RS_Pen(RS2::FlagInvalid)); arc->setLayer(NULL); letter->addEntity(arc); } } while (!line.isEmpty()); letter->calculateBorders(); letterList.add(letter); } } f.close(); }
void userPreferences::sFillList() { _hotkey->clear(); QString hotkey; QString action; char key; XTreeWidgetItem *last = 0; if (_currentUser->isChecked()) { for (key = '1'; key <= '9'; key++) { hotkey = QString("F%1").arg(key); action = _preferences->value(hotkey); if (!action.isNull()) last = new XTreeWidgetItem(_hotkey, last, -1, QVariant(tr("F%1").arg(key)), action, hotkey); } for (key = 'A'; key <= 'Z'; key++) { hotkey = QString("C%1").arg(key); action = _preferences->value(hotkey); if (!action.isNull()) last = new XTreeWidgetItem(_hotkey, last, -1, QVariant(QString("Ctrl+%1").arg(key)), action, hotkey); } for (key = '0'; key <= '9'; key++) { hotkey = QString("C%1").arg(key); action = _preferences->value(hotkey); if (!action.isNull()) last = new XTreeWidgetItem(_hotkey, last, -1, QVariant(QString("Ctrl+%1").arg(key)), action, hotkey); } } else { Preferences pref(_user->currentText()); for (key = '1'; key <= '9'; key++) { hotkey = QString("F%1").arg(key); action = pref.value(hotkey); if (!action.isNull()) last = new XTreeWidgetItem(_hotkey, last, -1, QVariant(tr("F%1").arg(key)), action, hotkey); } for (key = 'A'; key <= 'Z'; key++) { hotkey = QString("C%1").arg(key); action = pref.value(hotkey); if (!action.isNull()) last = new XTreeWidgetItem(_hotkey, last, -1,QVariant( QString("Ctrl+%1").arg(key)), action, hotkey); } for (key = '0'; key <= '9'; key++) { hotkey = QString("C%1").arg(key); action = pref.value(hotkey); if (!action.isNull()) last = new XTreeWidgetItem(_hotkey, last, -1, QVariant(QString("Ctrl+%1").arg(key)), action, hotkey); } } }
QFont KResourceMan::readFontEntry( const QString& rKey, const QFont* pDefault ) const { QFont aRetFont; QString aValue = readEntry( rKey ); if( !aValue.isNull() ) { // find first part (font family) int nIndex = aValue.find( ',' ); if( nIndex == -1 ) return aRetFont; aRetFont.setFamily( aValue.left( nIndex ) ); // find second part (point size) int nOldIndex = nIndex; nIndex = aValue.find( ',', nOldIndex+1 ); if( nIndex == -1 ) return aRetFont; aRetFont.setPointSize( aValue.mid( nOldIndex+1, nIndex-nOldIndex-1 ).toInt() ); // find third part (style hint) nOldIndex = nIndex; nIndex = aValue.find( ',', nOldIndex+1 ); if( nIndex == -1 ) return aRetFont; aRetFont.setStyleHint( (QFont::StyleHint)aValue.mid( nOldIndex+1, nIndex-nOldIndex-1 ).toUInt() ); // find fourth part (char set) nOldIndex = nIndex; nIndex = aValue.find( ',', nOldIndex+1 ); if( nIndex == -1 ) return aRetFont; aRetFont.setCharSet( (QFont::CharSet)aValue.mid( nOldIndex+1, nIndex-nOldIndex-1 ).toUInt() ); // find fifth part (weight) nOldIndex = nIndex; nIndex = aValue.find( ',', nOldIndex+1 ); if( nIndex == -1 ) return aRetFont; aRetFont.setWeight( aValue.mid( nOldIndex+1, nIndex-nOldIndex-1 ).toUInt() ); // find sixth part (font bits) uint nFontBits = aValue.right( aValue.length()-nIndex-1 ).toUInt(); if( nFontBits & 0x01 ) aRetFont.setItalic( true ); if( nFontBits & 0x02 ) aRetFont.setUnderline( true ); if( nFontBits & 0x04 ) aRetFont.setStrikeOut( true ); if( nFontBits & 0x08 ) aRetFont.setFixedPitch( true ); if( nFontBits & 0x20 ) aRetFont.setRawMode( true ); } else if( pDefault ) aRetFont = *pDefault; return aRetFont; }
void kdvi::applyPreferences() { QString s; config->setGroup( "kdvi" ); s = config->readEntry( "FontPath" ); if ( !s.isEmpty() && s != dviwin->fontPath() ) dviwin->setFontPath( s ); basedpi = config->readNumEntry( "BaseResolution" ); if ( basedpi <= 0 ) config->writeEntry( "BaseResolution", basedpi = 300 ); if ( basedpi != dviwin->resolution() ) dviwin->setResolution( basedpi ); mfmode = config->readEntry( "MetafontMode" ); if ( mfmode.isNull() ) config->writeEntry( "MetafontMode", mfmode = "/" ); if ( mfmode != dviwin->metafontMode() ) dviwin->setMetafontMode( mfmode ); paper = config->readEntry( "Paper" ); if ( paper.isNull() ) config->writeEntry( "Paper", paper = "A4" ); if ( paper != dviwin->paper() ) dviwin->setPaper( paper ); s = config->readEntry( "Gamma" ); if ( !s.isEmpty() && s.toFloat() != dviwin->gamma() ) dviwin->setGamma( s.toFloat() ); makepk = config->readNumEntry( "MakePK" ); applyMakePK(); showPS = config->readNumEntry( "ShowPS" ); applyShowPS(); dviwin->setAntiAlias( config->readNumEntry( "PS Anti Alias", 1 ) ); hideMenubar = config->readNumEntry( "HideMenubar" ); applyShowMenubar(); hideButtons = config->readNumEntry( "HideButtons" ); applyShowButtons(); vertToolbar = config->readNumEntry( "VertToolbar" ); applyVertToolbar(); hideStatusbar = config->readNumEntry( "HideStatusbar" ); applyShowStatusbar(); hideScrollbars = config->readNumEntry( "HideScrollbars" ); applyShowScrollbars(); smallShrink = config->readNumEntry( "SmallShrink" ); if (!smallShrink) smallShrink = 6; largeShrink = config->readNumEntry( "LargeShrink" ); if (!largeShrink) largeShrink = 2; config->setGroup( "RecentFiles" ); s = config->readEntry( "MaxCount" ); if ( s.isNull() || (recentmax = s.toInt())<=0 ) config->writeEntry( "MaxCount", recentmax = 10 ); int n = 0; recent.clear(); while ( n < recentmax ) { s = config->readEntry(QString().setNum(n++)); if ( !s.isEmpty() ) recent.insert( 0, s ); else break; } recentmenu->clear(); for (n=recent.count(); n-->0;) recentmenu->insertItem( recent.at(n), n, 0 ); config->setGroup( "kdvi" ); message(i18n("Preferences applied")); }
QVariant QDeclarativeFolderListModel::getMimeTypeImagePath(const QString file) const { QString fileLocal = file; QString filenameMD5 = QString(QCryptographicHash::hash(fileLocal.toUtf8(), QCryptographicHash::Md5) .toHex().toUpper()); if (mImageCache->isCached(filenameMD5)) return QVariant("image://plexydesk/" + filenameMD5); QFreeDesktopMime mime; QString mimeType = mime.fromFile(fileLocal); // qDebug() << "Requested mime info for: " << fileLocal << " -> " << mimeType; QString imgfile; QString theme = PlexyDesk::Config::getInstance()->themepackName(); if (mimeType.isNull()) mimeType = ""; if (mimeType.contains("inode/directory", Qt::CaseInsensitive)) imgfile = "folder.png"; /* Executables */ else if (mimeType.contains("ms-dos", Qt::CaseInsensitive)) imgfile = "exe.png"; else if (mimeType.contains("x-executable", Qt::CaseInsensitive)) imgfile = "obj.png"; else if (mimeType.contains("sharedlib", Qt::CaseInsensitive)) imgfile = "so.png"; else if (mimeType.contains("library-la", Qt::CaseInsensitive)) imgfile = "la.png"; else if(mimeType.contains("shellscript", Qt::CaseInsensitive)) imgfile = "script.png"; else if(mimeType.contains("x-desktop", Qt::CaseInsensitive)) imgfile = "exec.png"; /* Sources */ else if (mimeType.contains("x-c++src", Qt::CaseInsensitive)) imgfile = "cpp.png"; else if (mimeType.contains("x-csrc", Qt::CaseInsensitive)) imgfile = "c.png"; else if (mimeType.contains("x-chdr", Qt::CaseInsensitive)) imgfile = "h.png"; else if (mimeType.contains("x-object", Qt::CaseInsensitive)) imgfile = "obj.png"; /* Int. Lang. */ else if (mimeType.contains("x-php", Qt::CaseInsensitive)) imgfile = "php.png"; else if (mimeType.contains("x-perl", Qt::CaseInsensitive)) imgfile = "pl.png"; else if (mimeType.contains("x-python", Qt::CaseInsensitive)) imgfile = "py.png"; else if (mimeType.contains("x-java", Qt::CaseInsensitive)) imgfile = "java.png"; else if (mimeType.contains("javascript", Qt::CaseInsensitive)) imgfile = "js.png"; else if (mimeType.contains("x-ruby", Qt::CaseInsensitive)) imgfile = "rb.png"; else if (mimeType.contains("application/xml", Qt::CaseInsensitive)) imgfile = "xml.png"; /* Documents */ else if(mimeType.contains("pdf", Qt::CaseInsensitive)) imgfile = "pdf.png"; else if(mimeType.contains("text/plain", Qt::CaseInsensitive)) imgfile = "txt.png"; else if(mimeType.contains(QRegExp("rtf|msword|wordprocessing|opendocument.text", Qt::CaseInsensitive))) imgfile = "doc.png"; else if(mimeType.contains(QRegExp("ms-excel|spreadsheet", Qt::CaseInsensitive))) imgfile = "xls.png"; else if(mimeType.contains(QRegExp("ms-powerpoint|presentation", Qt::CaseInsensitive))) imgfile = "ppt.png"; else if(mimeType.contains("database", Qt::CaseInsensitive)) imgfile = "odb.png"; else if (mimeType.contains("html", Qt::CaseInsensitive)) imgfile = "html.png"; else if (mimeType.contains("x-uri", Qt::CaseInsensitive)) imgfile = "url.png"; /* Images */ else if (mimeType.contains("image/svg", Qt::CaseInsensitive)) imgfile = "svg.png"; else if (mimeType.contains("image/", Qt::CaseInsensitive)) imgfile = "img.png"; /* Archives */ else if (mimeType.contains(QRegExp("ms-cab|stuffit|/zip|x-(compressed|(r|t)ar|7z|(g|b)zip)", Qt::CaseInsensitive))) imgfile = "archive.png"; /* Video */ else if (mimeType.contains("video/", Qt::CaseInsensitive)) imgfile = "video.png"; /* Audio */ else if (mimeType.contains("audio/", Qt::CaseInsensitive)) imgfile = "audio.png"; /* Disc Images */ else if (mimeType.contains("cd-image", Qt::CaseInsensitive)) imgfile = "iso.png"; /* Packages */ else if (mimeType.contains(QRegExp("x-(apple-diskimage|rpm|deb|msi)", Qt::CaseInsensitive))) imgfile = "package.png"; /* Misc */ else if (mimeType.contains("bittorrent", Qt::CaseInsensitive)) imgfile = "torrent.png"; /* Unknown */ else imgfile = "unknown.png"; mImageCache->addToCached(imgfile, filenameMD5, theme); return QVariant("image://plexydesk/" + filenameMD5); }
bool AnalyserBeats::loadStored(TrackPointer tio) const { int iMinBpm; int iMaxBpm; bool allow_above = static_cast<bool>(m_pConfig->getValueString( ConfigKey(BPM_CONFIG_KEY, BPM_ABOVE_RANGE_ENABLED)).toInt()); if (allow_above) { iMinBpm = 0; iMaxBpm = 9999; } else { iMinBpm = m_pConfig->getValueString(ConfigKey(BPM_CONFIG_KEY, BPM_RANGE_START)).toInt(); iMaxBpm = m_pConfig->getValueString(ConfigKey(BPM_CONFIG_KEY, BPM_RANGE_END)).toInt(); } bool bPreferencesFixedTempo = static_cast<bool>( m_pConfig->getValueString( ConfigKey(BPM_CONFIG_KEY, BPM_FIXED_TEMPO_ASSUMPTION)).toInt()); bool bPreferencesOffsetCorrection = static_cast<bool>( m_pConfig->getValueString( ConfigKey(BPM_CONFIG_KEY, BPM_FIXED_TEMPO_OFFSET_CORRECTION)).toInt()); bool bPreferencesReanalyzeOldBpm = static_cast<bool>( m_pConfig->getValueString( ConfigKey(BPM_CONFIG_KEY, BPM_REANALYZE_WHEN_SETTINGS_CHANGE)).toInt()); bool bPreferencesFastAnalysis = static_cast<bool>( m_pConfig->getValueString( ConfigKey(BPM_CONFIG_KEY, BPM_FAST_ANALYSIS_ENABLED)).toInt()); bool bpmLock = tio->hasBpmLock(); if (bpmLock) { qDebug() << "Track is BpmLocked: Beat calculation will not start"; return true; } QString library = m_pConfig->getValueString( ConfigKey(VAMP_CONFIG_KEY, VAMP_ANALYSER_BEAT_LIBRARY)); QString pluginID = m_pConfig->getValueString( ConfigKey(VAMP_CONFIG_KEY, VAMP_ANALYSER_BEAT_PLUGIN_ID)); // At first start config for QM and Vamp does not exist --> set default // TODO(XXX): This is no longer present in initialise. Remove? if (library.isEmpty() || library.isNull()) library = "libmixxxminimal"; if (pluginID.isEmpty() || pluginID.isNull()) pluginID="qm-tempotracker:0"; // If the track already has a Beats object then we need to decide whether to // analyze this track or not. BeatsPointer pBeats = tio->getBeats(); if (pBeats) { QString version = pBeats->getVersion(); QString subVersion = pBeats->getSubVersion(); QHash<QString, QString> extraVersionInfo = getExtraVersionInfo( pluginID, bPreferencesFastAnalysis); QString newVersion = BeatFactory::getPreferredVersion( bPreferencesOffsetCorrection); QString newSubVersion = BeatFactory::getPreferredSubVersion( bPreferencesFixedTempo, bPreferencesOffsetCorrection, iMinBpm, iMaxBpm, extraVersionInfo); if (version == newVersion && subVersion == newSubVersion) { // If the version and settings have not changed then if the world is // sane, re-analyzing will do nothing. qDebug() << "Beat sub-version has not changed since previous analysis so not analyzing."; return true; } else if (bPreferencesReanalyzeOldBpm) { return false; } else if (pBeats->getBpm() == 0.0) { qDebug() << "BPM is 0 for track so re-analyzing despite preference settings."; return false; } else if (pBeats->findNextBeat(0) <= 0.0) { qDebug() << "First beat is 0 for grid so analyzing track to find first beat."; return false; } else { qDebug() << "Beat calculation skips analyzing because the track has" << "a BPM computed by a previous Mixxx version and user" << "preferences indicate we should not change it."; return true; } } else { // If we got here, we want to analyze this track. return false; } }
int Option::init(int argc, char **argv) { Option::application_argv0 = 0; Option::cpp_moc_mod = ""; Option::h_moc_mod = "moc_"; Option::lex_mod = "_lex"; Option::yacc_mod = "_yacc"; Option::prl_ext = ".prl"; Option::libtool_ext = ".la"; Option::pkgcfg_ext = ".pc"; Option::prf_ext = ".prf"; Option::js_ext = ".js"; Option::ui_ext = ".ui"; Option::h_ext << ".h" << ".hpp" << ".hh" << ".hxx"; Option::c_ext << ".c"; #ifndef Q_OS_WIN Option::h_ext << ".H"; #endif Option::cpp_moc_ext = ".moc"; Option::h_moc_ext = ".cpp"; Option::cpp_ext << ".cpp" << ".cc" << ".cxx"; #ifndef Q_OS_WIN Option::cpp_ext << ".C"; #endif Option::lex_ext = ".l"; Option::yacc_ext = ".y"; Option::pro_ext = ".pro"; Option::mmp_ext = ".mmp"; #ifdef Q_OS_WIN Option::dirlist_sep = ";"; Option::shellPath = detectShellPath(); Option::res_ext = ".res"; #else Option::dirlist_sep = ":"; Option::shellPath = QStringList("sh"); #endif Option::sysenv_mod = "QMAKE_ENV_"; Option::field_sep = ' '; if(argc && argv) { Option::application_argv0 = argv[0]; QString argv0 = argv[0]; if(Option::qmake_mode == Option::QMAKE_GENERATE_NOTHING) Option::qmake_mode = default_mode(argv0); if(!argv0.isEmpty() && !QFileInfo(argv0).isRelative()) { Option::qmake_abslocation = argv0; } else if (argv0.contains(QLatin1Char('/')) #ifdef Q_OS_WIN || argv0.contains(QLatin1Char('\\')) #endif ) { //relative PWD Option::qmake_abslocation = QDir::current().absoluteFilePath(argv0); } else { //in the PATH QByteArray pEnv = qgetenv("PATH"); QDir currentDir = QDir::current(); #ifdef Q_OS_WIN QStringList paths = QString::fromLocal8Bit(pEnv).split(QLatin1String(";")); #else QStringList paths = QString::fromLocal8Bit(pEnv).split(QLatin1String(":")); #endif for (QStringList::const_iterator p = paths.constBegin(); p != paths.constEnd(); ++p) { if ((*p).isEmpty()) continue; QString candidate = currentDir.absoluteFilePath(*p + QLatin1Char('/') + argv0); #ifdef Q_OS_WIN candidate += ".exe"; #endif if (QFile::exists(candidate)) { Option::qmake_abslocation = candidate; break; } } } if(!Option::qmake_abslocation.isNull()) Option::qmake_abslocation = QDir::cleanPath(Option::qmake_abslocation); } else { Option::qmake_mode = Option::QMAKE_GENERATE_MAKEFILE; } const QByteArray envflags = qgetenv("QMAKEFLAGS"); if (!envflags.isNull()) { int env_argc = 0, env_size = 0, currlen=0; char quote = 0, **env_argv = NULL; for (int i = 0; i < envflags.size(); ++i) { if (!quote && (envflags.at(i) == '\'' || envflags.at(i) == '"')) { quote = envflags.at(i); } else if (envflags.at(i) == quote) { quote = 0; } else if (!quote && envflags.at(i) == ' ') { if (currlen && env_argv && env_argv[env_argc]) { env_argv[env_argc][currlen] = '\0'; currlen = 0; env_argc++; } } else { if(!env_argv || env_argc > env_size) { env_argv = (char **)realloc(env_argv, sizeof(char *)*(env_size+=10)); for(int i2 = env_argc; i2 < env_size; i2++) env_argv[i2] = NULL; } if(!env_argv[env_argc]) { currlen = 0; env_argv[env_argc] = (char*)malloc(255); } if(currlen < 255) env_argv[env_argc][currlen++] = envflags.at(i); } } if(env_argv) { if(env_argv[env_argc]) { env_argv[env_argc][currlen] = '\0'; currlen = 0; env_argc++; } parseCommandLine(env_argc, env_argv); for(int i2 = 0; i2 < env_size; i2++) { if(env_argv[i2]) free(env_argv[i2]); } free(env_argv); } } if(argc && argv) { int ret = parseCommandLine(argc, argv, 1); if(ret != Option::QMAKE_CMDLINE_SUCCESS) { if ((ret & Option::QMAKE_CMDLINE_SHOW_USAGE) != 0) usage(argv[0]); return ret; //return ret == QMAKE_CMDLINE_SHOW_USAGE ? usage(argv[0]) : false; } } //last chance for defaults if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE || Option::qmake_mode == Option::QMAKE_GENERATE_PRL) { if(Option::mkfile::qmakespec.isNull() || Option::mkfile::qmakespec.isEmpty()) Option::mkfile::qmakespec = QString::fromLocal8Bit(qgetenv("QMAKESPEC").constData()); //try REALLY hard to do it for them, lazy.. if(Option::mkfile::project_files.isEmpty()) { QString proj = detectProjectFile(qmake_getpwd()); if(!proj.isNull()) Option::mkfile::project_files.append(proj); #ifndef QT_BUILD_QMAKE_LIBRARY if(Option::mkfile::project_files.isEmpty()) { usage(argv[0]); return Option::QMAKE_CMDLINE_ERROR; } #endif } } else if (Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT) { #if defined(Q_OS_MAC) Option::host_mode = Option::HOST_MACX_MODE; Option::target_mode = Option::TARG_MACX_MODE; #elif defined(Q_OS_UNIX) Option::host_mode = Option::HOST_UNIX_MODE; Option::target_mode = Option::TARG_UNIX_MODE; #else Option::host_mode = Option::HOST_WIN_MODE; Option::target_mode = Option::TARG_WIN_MODE; #endif } //defaults for globals if (Option::host_mode != Option::HOST_UNKNOWN_MODE) applyHostMode(); return QMAKE_CMDLINE_SUCCESS; }
int Option::parseCommandLine(int argc, char **argv, int skip) { bool before = true; for(int x = skip; x < argc; x++) { if(*argv[x] == '-' && strlen(argv[x]) > 1) { /* options */ QString opt = argv[x] + 1; //first param is a mode, or we default if(x == 1) { bool specified = true; if(opt == "project") { Option::recursive = Option::QMAKE_RECURSIVE_YES; Option::qmake_mode = Option::QMAKE_GENERATE_PROJECT; } else if(opt == "prl") { Option::mkfile::do_deps = false; Option::mkfile::do_mocs = false; Option::qmake_mode = Option::QMAKE_GENERATE_PRL; } else if(opt == "set") { Option::qmake_mode = Option::QMAKE_SET_PROPERTY; } else if(opt == "unset") { Option::qmake_mode = Option::QMAKE_UNSET_PROPERTY; } else if(opt == "query") { Option::qmake_mode = Option::QMAKE_QUERY_PROPERTY; } else if(opt == "makefile") { Option::qmake_mode = Option::QMAKE_GENERATE_MAKEFILE; } else { specified = false; } if(specified) continue; } //all modes if(opt == "o" || opt == "output") { Option::output.setFileName(argv[++x]); } else if(opt == "after") { before = false; } else if(opt == "t" || opt == "template") { Option::user_template = argv[++x]; } else if(opt == "tp" || opt == "template_prefix") { Option::user_template_prefix = argv[++x]; } else if(opt == "macx") { fprintf(stderr, "-macx is deprecated.\n"); Option::host_mode = HOST_MACX_MODE; Option::target_mode = TARG_MACX_MODE; Option::target_mode_overridden = true; } else if(opt == "unix") { fprintf(stderr, "-unix is deprecated.\n"); Option::host_mode = HOST_UNIX_MODE; Option::target_mode = TARG_UNIX_MODE; Option::target_mode_overridden = true; } else if(opt == "win32") { fprintf(stderr, "-win32 is deprecated.\n"); Option::host_mode = HOST_WIN_MODE; Option::target_mode = TARG_WIN_MODE; Option::target_mode_overridden = true; } else if(opt == "integrity") { Option::target_mode = TARG_INTEGRITY_MODE; } else if(opt == "d") { Option::debug_level++; } else if(opt == "version" || opt == "v" || opt == "-version") { fprintf(stdout, "QMake version %s\n" "Using Qt version %s in %s\n", qmake_version(), QT_VERSION_STR, QLibraryInfo::location(QLibraryInfo::LibrariesPath).toLatin1().constData()); #ifdef QMAKE_OPENSOURCE_VERSION fprintf(stdout, "QMake is Open Source software from Nokia Corporation and/or its subsidiary(-ies).\n"); #endif return Option::QMAKE_CMDLINE_BAIL; } else if(opt == "h" || opt == "help") { return Option::QMAKE_CMDLINE_SHOW_USAGE; } else if(opt == "Wall") { Option::warn_level |= WarnAll; } else if(opt == "Wparser") { Option::warn_level |= WarnParser; } else if(opt == "Wlogic") { Option::warn_level |= WarnLogic; } else if(opt == "Wdeprecated") { Option::warn_level |= WarnDeprecated; } else if(opt == "Wnone") { Option::warn_level = WarnNone; } else if(opt == "r" || opt == "recursive") { Option::recursive = Option::QMAKE_RECURSIVE_YES; } else if(opt == "nr" || opt == "norecursive") { Option::recursive = Option::QMAKE_RECURSIVE_NO; } else if(opt == "config") { Option::user_configs += argv[++x]; } else { if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE || Option::qmake_mode == Option::QMAKE_GENERATE_PRL) { if(opt == "nodepend" || opt == "nodepends") { Option::mkfile::do_deps = false; } else if(opt == "nomoc") { Option::mkfile::do_mocs = false; } else if(opt == "nocache") { Option::mkfile::do_cache = false; } else if(opt == "createstub") { Option::mkfile::do_stub_makefile = true; } else if(opt == "nodependheuristics") { Option::mkfile::do_dep_heuristics = false; } else if(opt == "E") { fprintf(stderr, "-E is deprecated. Use -d instead.\n"); Option::mkfile::do_preprocess = true; } else if(opt == "cache") { Option::mkfile::cachefile = argv[++x]; } else if(opt == "platform" || opt == "spec") { Option::mkfile::qmakespec = argv[++x]; Option::mkfile::qmakespec_commandline = argv[x]; } else { fprintf(stderr, "***Unknown option -%s\n", opt.toLatin1().constData()); return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } } else if(Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT) { if(opt == "nopwd") { Option::projfile::do_pwd = false; } else { fprintf(stderr, "***Unknown option -%s\n", opt.toLatin1().constData()); return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } } } } else { QString arg = argv[x]; if(arg.indexOf('=') != -1) { if(before) Option::before_user_vars.append(arg); else Option::after_user_vars.append(arg); } else { bool handled = true; if(Option::qmake_mode == Option::QMAKE_QUERY_PROPERTY || Option::qmake_mode == Option::QMAKE_SET_PROPERTY || Option::qmake_mode == Option::QMAKE_UNSET_PROPERTY) { Option::prop::properties.append(arg); } else { QFileInfo fi(arg); if(!fi.makeAbsolute()) //strange arg = fi.filePath(); if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE || Option::qmake_mode == Option::QMAKE_GENERATE_PRL) { if(fi.isDir()) { QString proj = detectProjectFile(arg); if (!proj.isNull()) arg = proj; } Option::mkfile::project_files.append(arg); } else if(Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT) { Option::projfile::project_dirs.append(arg); } else { handled = false; } } if(!handled) { return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } } } } return Option::QMAKE_CMDLINE_SUCCESS; }
void wavrMessageLog::appendMessageLog(MessageType type, QString *lpszUserId, QString *lpszUserName, wavrXmlMessage *pMessage, bool bReload) { if(!pMessage && type != MT_Error) return; QString message; QString html; QString caption; QDateTime time; QFont font; QColor color; QString fontStyle; QString id = QString::null; bool addToLog = true; removeMessageLog("_wavr_statediv"); switch(type) { case MT_Message: time.setMSecsSinceEpoch(pMessage->header(XML_TIME).toLongLong()); message = pMessage->data(XML_MESSAGE); font.fromString(pMessage->data(XML_FONT)); color.setNamedColor(pMessage->data(XML_COLOR)); qDebug() << "message received is " << message; appendMessage(lpszUserId, lpszUserName, &message, &time, &font, &color); lastId = *lpszUserId; break; case MT_Broadcast: time.setMSecsSinceEpoch(pMessage->header(XML_TIME).toLongLong()); message = pMessage->data(XML_BROADCAST); appendBroadcast(lpszUserId, lpszUserName, &message, &time); lastId = QString::null; break; case MT_ChatState: message = pMessage->data(XML_CHATSTATE); caption = getChatStateMessage((ChatState)wavrHelper::indexOf(ChatStateNames, CS_Max, message)); qDebug() << "chatstate message " << message << " caption: " << caption; if(!caption.isNull()) { html = themeData.stateMsg; html.replace("%iconpath%", "qrc"IDR_BLANK); html.replace("%sender%", caption.arg(*lpszUserName)); html.replace("%message%", ""); appendMessageLog(&html); } addToLog = false; break; case MT_Failed: message = pMessage->data(XML_MESSAGE); font.fromString(pMessage->data(XML_FONT)); color.setNamedColor(pMessage->data(XML_COLOR)); html = themeData.sysMsg; caption = tr("Message not delivered to %1:"); fontStyle = getFontStyle(&font, &color, true); decodeMessage(&message); html.replace("%iconpath%", "qrc"IDR_CRITICALMSG); html.replace("%sender%", caption.arg(*lpszUserName)); html.replace("%style%", fontStyle); html.replace("%message%", message); appendMessageLog(&html); lastId = QString::null; break; case MT_Error: html = themeData.sysMsg; html.replace("%iconpath%", "qrc"IDR_CRITICALMSG); html.replace("%sender%", tr("Your message was not sent.")); html.replace("%message%", ""); appendMessageLog(&html); lastId = QString::null; addToLog = false; break; case MT_File: case MT_Folder: appendFileMessage(type, lpszUserName, pMessage, bReload); id = pMessage->data(XML_TEMPID); pMessage->removeData(XML_TEMPID); lastId = QString::null; break; default: break; } if(!bReload && addToLog && pMessage) { wavrXmlMessage xmlMessage = pMessage->clone(); QString userId = lpszUserId ? *lpszUserId : QString::null; QString userName = lpszUserName ? *lpszUserName : QString::null; messageLog.append(SingleMessage(type, userId, userName, xmlMessage, id)); } }
int Option::init(int argc, char **argv) { Option::prf_ext = ".prf"; Option::pro_ext = ".pro"; Option::field_sep = ' '; if(argc && argv) { QString argv0 = argv[0]; if(Option::qmake_mode == Option::QMAKE_GENERATE_NOTHING) Option::qmake_mode = default_mode(argv0); if(!argv0.isEmpty() && !QFileInfo(argv0).isRelative()) { globals->qmake_abslocation = argv0; } else if (argv0.contains(QLatin1Char('/')) #ifdef Q_OS_WIN || argv0.contains(QLatin1Char('\\')) #endif ) { //relative PWD globals->qmake_abslocation = QDir::current().absoluteFilePath(argv0); } else { //in the PATH QByteArray pEnv = qgetenv("PATH"); QDir currentDir = QDir::current(); #ifdef Q_OS_WIN QStringList paths = QString::fromLocal8Bit(pEnv).split(QLatin1String(";")); paths.prepend(QLatin1String(".")); #else QStringList paths = QString::fromLocal8Bit(pEnv).split(QLatin1String(":")); #endif for (QStringList::const_iterator p = paths.constBegin(); p != paths.constEnd(); ++p) { if ((*p).isEmpty()) continue; QString candidate = currentDir.absoluteFilePath(*p + QLatin1Char('/') + argv0); #ifdef Q_OS_WIN if (!candidate.endsWith(QLatin1String(".exe"))) candidate += QLatin1String(".exe"); #endif if (QFile::exists(candidate)) { globals->qmake_abslocation = candidate; break; } } } if (!globals->qmake_abslocation.isNull()) globals->qmake_abslocation = QDir::cleanPath(globals->qmake_abslocation); else // This is rather unlikely to ever happen on a modern system ... globals->qmake_abslocation = QLibraryInfo::rawLocation(QLibraryInfo::HostBinariesPath, QLibraryInfo::EffectivePaths) + #ifdef Q_OS_WIN "/qmake.exe"; #else "/qmake"; #endif } else { Option::qmake_mode = Option::QMAKE_GENERATE_MAKEFILE; } QMakeCmdLineParserState cmdstate(QDir::currentPath()); const QByteArray envflags = qgetenv("QMAKEFLAGS"); if (!envflags.isNull()) { QStringList args; QByteArray buf = ""; char quote = 0; bool hasWord = false; for (int i = 0; i < envflags.size(); ++i) { char c = envflags.at(i); if (!quote && (c == '\'' || c == '"')) { quote = c; } else if (c == quote) { quote = 0; } else if (!quote && c == ' ') { if (hasWord) { args << QString::fromLocal8Bit(buf); hasWord = false; buf = ""; } } else { buf += c; hasWord = true; } } if (hasWord) args << QString::fromLocal8Bit(buf); parseCommandLine(args, cmdstate); cmdstate.flush(); } if(argc && argv) { QStringList args; for (int i = 1; i < argc; i++) args << QString::fromLocal8Bit(argv[i]); while (!args.isEmpty()) { QString opt = args.at(0); if (opt == "-project") { Option::recursive = true; Option::qmake_mode = Option::QMAKE_GENERATE_PROJECT; } else if (opt == "-prl") { Option::mkfile::do_deps = false; Option::mkfile::do_mocs = false; Option::qmake_mode = Option::QMAKE_GENERATE_PRL; } else if (opt == "-set") { Option::qmake_mode = Option::QMAKE_SET_PROPERTY; } else if (opt == "-unset") { Option::qmake_mode = Option::QMAKE_UNSET_PROPERTY; } else if (opt == "-query") { Option::qmake_mode = Option::QMAKE_QUERY_PROPERTY; } else if (opt == "-makefile") { Option::qmake_mode = Option::QMAKE_GENERATE_MAKEFILE; } else { break; } args.takeFirst(); break; } int ret = parseCommandLine(args, cmdstate); if(ret != Option::QMAKE_CMDLINE_SUCCESS) { if ((ret & Option::QMAKE_CMDLINE_SHOW_USAGE) != 0) usage(argv[0]); return ret; //return ret == QMAKE_CMDLINE_SHOW_USAGE ? usage(argv[0]) : false; } globals->qmake_args = args; } globals->commitCommandLineArguments(cmdstate); globals->debugLevel = Option::debug_level; //last chance for defaults if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE || Option::qmake_mode == Option::QMAKE_GENERATE_PRL) { globals->useEnvironment(); //try REALLY hard to do it for them, lazy.. if(Option::mkfile::project_files.isEmpty()) { QString proj = detectProjectFile(qmake_getpwd()); if(!proj.isNull()) Option::mkfile::project_files.append(proj); #ifndef QT_BUILD_QMAKE_LIBRARY if(Option::mkfile::project_files.isEmpty()) { usage(argv[0]); return Option::QMAKE_CMDLINE_ERROR; } #endif } } return QMAKE_CMDLINE_SUCCESS; }
void QgsSearchQueryBuilder::loadQuery() { QSettings s; QString lastQueryFileDir = s.value( "/UI/lastQueryFileDir", QDir::homePath() ).toString(); QString queryFileName = QFileDialog::getOpenFileName( nullptr, tr( "Load query from file" ), lastQueryFileDir, tr( "Query files" ) + " (*.qqf);;" + tr( "All files" ) + " (*)" ); if ( queryFileName.isNull() ) { return; } QFile queryFile( queryFileName ); if ( !queryFile.open( QIODevice::ReadOnly ) ) { QMessageBox::critical( nullptr, tr( "Error" ), tr( "Could not open file for reading" ) ); return; } QDomDocument queryDoc; if ( !queryDoc.setContent( &queryFile ) ) { QMessageBox::critical( nullptr, tr( "Error" ), tr( "File is not a valid xml document" ) ); return; } QDomElement queryElem = queryDoc.firstChildElement( "Query" ); if ( queryElem.isNull() ) { QMessageBox::critical( nullptr, tr( "Error" ), tr( "File is not a valid query document" ) ); return; } QString query = queryElem.text(); //todo: test if all the attributes are valid QgsExpression search( query ); if ( search.hasParserError() ) { QMessageBox::critical( this, tr( "Search string parsing error" ), search.parserErrorString() ); return; } QString newQueryText = query; #if 0 // TODO: implement with visitor pattern in QgsExpression QStringList attributes = searchTree->referencedColumns(); QMap< QString, QString> attributesToReplace; QStringList existingAttributes; //get all existing fields QMap<QString, int>::const_iterator fieldIt = mFieldMap.constBegin(); for ( ; fieldIt != mFieldMap.constEnd(); ++fieldIt ) { existingAttributes.push_back( fieldIt.key() ); } //if a field does not exist, ask what field should be used instead QStringList::const_iterator attIt = attributes.constBegin(); for ( ; attIt != attributes.constEnd(); ++attIt ) { //test if attribute is there if ( !mFieldMap.contains( *attIt ) ) { bool ok; QString replaceAttribute = QInputDialog::getItem( 0, tr( "Select attribute" ), tr( "There is no attribute '%1' in the current vector layer. Please select an existing attribute" ).arg( *attIt ), existingAttributes, 0, false, &ok ); if ( !ok || replaceAttribute.isEmpty() ) { return; } attributesToReplace.insert( *attIt, replaceAttribute ); } } //Now replace all the string in the query QList<QgsSearchTreeNode*> columnRefList = searchTree->columnRefNodes(); QList<QgsSearchTreeNode*>::iterator columnIt = columnRefList.begin(); for ( ; columnIt != columnRefList.end(); ++columnIt ) { QMap< QString, QString>::const_iterator replaceIt = attributesToReplace.find(( *columnIt )->columnRef() ); if ( replaceIt != attributesToReplace.constEnd() ) { ( *columnIt )->setColumnRef( replaceIt.value() ); } } if ( attributesToReplace.size() > 0 ) { newQueryText = query; } #endif txtSQL->clear(); txtSQL->insertText( newQueryText ); }
void QgsVectorGradientColorRampV2Dialog::on_btnInformation_pressed() { if ( mRamp->info().isEmpty() ) return; QgsDialog *dlg = new QgsDialog( this ); QLabel *label = nullptr; // information table QTableWidget *tableInfo = new QTableWidget( dlg ); tableInfo->verticalHeader()->hide(); tableInfo->horizontalHeader()->hide(); tableInfo->setRowCount( mRamp->info().count() ); tableInfo->setColumnCount( 2 ); int i = 0; QgsStringMap rampInfo = mRamp->info(); for ( QgsStringMap::const_iterator it = rampInfo.constBegin(); it != rampInfo.constEnd(); ++it ) { if ( it.key().startsWith( "cpt-city" ) ) continue; tableInfo->setItem( i, 0, new QTableWidgetItem( it.key() ) ); tableInfo->setItem( i, 1, new QTableWidgetItem( it.value() ) ); tableInfo->resizeRowToContents( i ); i++; } tableInfo->resizeColumnToContents( 0 ); tableInfo->horizontalHeader()->setStretchLastSection( true ); tableInfo->setRowCount( i ); tableInfo->setFixedHeight( tableInfo->rowHeight( 0 ) * i + 5 ); dlg->layout()->addWidget( tableInfo ); dlg->resize( 600, 250 ); dlg->layout()->addSpacing( 5 ); // gradient file QString gradientFile = mRamp->info().value( "cpt-city-gradient" ); if ( ! gradientFile.isNull() ) { QString fileName = gradientFile; fileName.replace( "<cpt-city>", QgsCptCityArchive::defaultBaseDir() ); if ( ! QFile::exists( fileName ) ) { fileName = gradientFile; fileName.replace( "<cpt-city>", "http://soliton.vm.bytemark.co.uk/pub/cpt-city" ); } label = new QLabel( tr( "Gradient file : %1" ).arg( fileName ), dlg ); label->setTextInteractionFlags( Qt::TextBrowserInteraction ); dlg->layout()->addSpacing( 5 ); dlg->layout()->addWidget( label ); } // license file QString licenseFile = mRamp->info().value( "cpt-city-license" ); if ( !licenseFile.isNull() ) { QString fileName = licenseFile; fileName.replace( "<cpt-city>", QgsCptCityArchive::defaultBaseDir() ); if ( ! QFile::exists( fileName ) ) { fileName = licenseFile; fileName.replace( "<cpt-city>", "http://soliton.vm.bytemark.co.uk/pub/cpt-city" ); } label = new QLabel( tr( "License file : %1" ).arg( fileName ), dlg ); label->setTextInteractionFlags( Qt::TextBrowserInteraction ); dlg->layout()->addSpacing( 5 ); dlg->layout()->addWidget( label ); if ( QFile::exists( fileName ) ) { QTextEdit *textEdit = new QTextEdit( dlg ); textEdit->setReadOnly( true ); QFile file( fileName ); if ( file.open( QIODevice::ReadOnly | QIODevice::Text ) ) { textEdit->setText( file.readAll() ); file.close(); dlg->layout()->addSpacing( 5 ); dlg->layout()->addWidget( textEdit ); dlg->resize( 600, 500 ); } } } dlg->show(); //non modal }
bool SkinSogou::loadSkin(const QString skinPath) { init(); QFile sogouSkinConfFile(skinPath + "skin.ini"); if (!sogouSkinConfFile.exists()) return false; if (!sogouSkinConfFile.open(QIODevice::ReadOnly)) return false; QString line; QString key, value; /// parse ini file content bool general = false; bool display = false; bool scheme_h1 = false; bool scheme_v1 = false; bool statusbar = false; int h_pt, h_pb, h_pl, h_pr; int v_pt, v_pb, v_pl, v_pr; unsigned int pinyin_color, zhongwen_color, zhongwen_first_color, comphint_color; int fontPixelSize = 12; setAdjustWidth(10); setAdjustHeight(30); setHorizontalTileMode("Stretch"); setVerticalTileMode("Stretch"); setInputStringPosX(0); setInputStringPosY(0); setOutputCandPosX(0); setOutputCandPosY(0); QTextStream textStream(sogouSkinConfFile.readAll()); do { line = textStream.readLine(); if (line.isEmpty() || line.at(0) == '#') continue; if (line.at(0) == '[') { general = (line == "[General]"); display = (line == "[Display]"); scheme_h1 = (line == "[Scheme_H1]"); scheme_v1 = (line == "[Scheme_V1]"); statusbar = (line == "[StatusBar]"); continue; } if (!line.contains('=')) continue; key = line.split('=').at(0); value = line.split('=').at(1); if (value.isEmpty()) continue; if (display) { if (key == "font_size") setFontSize(value.toInt()); else if (key == "pinyin_color"){ pinyin_color = value.toUInt(0, 0); setInputColor(QColor(qBlue(pinyin_color), qGreen(pinyin_color), qRed(pinyin_color))); } else if (key == "zhongwen_color"){ zhongwen_color = value.toUInt(0, 0); setOtherColor(QColor(qBlue(zhongwen_color), qGreen(zhongwen_color), qRed(zhongwen_color))); } else if (key == "zhongwen_first_color"){ zhongwen_first_color = value.toUInt(0, 0); setFirstCandColor(QColor(qBlue(zhongwen_first_color), qGreen(zhongwen_first_color), qRed(zhongwen_first_color))); } else if (key == "comphint_color"){ //FIXME //comphint_color = value.toUInt(0, 0); } }else if (scheme_h1) { if (key == "pic" && MainModel::self()->isHorizontal()) { setInputBackImg("file:/" + skinPath + value); } else if (key == "pinyin_marge") { QStringList list = value.split(','); h_pt = list.at(0).trimmed().toInt(); h_pb = list.at(1).trimmed().toInt(); h_pl = list.at(2).trimmed().toInt(); h_pr = list.at(3).trimmed().toInt(); if (MainModel::self()->isHorizontal()){ setMarginTop(h_pt); setMarginBottom(h_pb); setMarginLeft(h_pl); setMarginRight(h_pr); } } else if (key == "custom0_align") { //todo } else if (key == "custom0") { mCustomImgH1[0] = value; setCustomImg0 ("file:/" + skinPath + value); } else if (key == "custom1") { mCustomImgH1[1] = value; setCustomImg1 ("file:/" + skinPath + value); } else if (key == "custom_cnt") { mCustomCntH1 = value.toInt(); } }else if (scheme_v1) { if (key == "pic" && !MainModel::self()->isHorizontal()) { setInputBackImg("file:/" + skinPath + value); } else if (key == "pinyin_marge") { QStringList list = value.split(','); v_pt = list.at(0).trimmed().toInt(); v_pb = list.at(1).trimmed().toInt(); v_pl = list.at(2).trimmed().toInt(); v_pr = list.at(3).trimmed().toInt(); if (!MainModel::self()->isHorizontal()){ setMarginTop(v_pt); setMarginBottom(v_pb); setMarginLeft(v_pl); setMarginRight(v_pr); } } else if (key == "custom0") { mCustomImgV1[0] = value; //qDebug() << "cuystom0 " << value; //setCustomImg0(value); } else if (key == "custom1") { mCustomImgV1[1] = value; qDebug() << "cuystom1 " << value; //setCustomImg1(value); } else if (key == "custom_cnt") { mCustomCntV1 = value.toInt(); //qDebug() << "cuystom_cnt " << mCustomCntV1; } } else if (statusbar) { if (key == "pic") { //FIXME //setTipsImg("file:/" + skinPath + value); } } } while (!line.isNull()); sogouSkinConfFile.close(); return true; }
void RS_Font::readLFF(QString path) { QString line; QFile f(path); encoding = "UTF-8"; f.open(QIODevice::ReadOnly); QTextStream ts(&f); // Read line by line until we find a new letter: while (!ts.atEnd()) { line = ts.readLine(); if (line.isEmpty()) continue; // Read font settings: if (line.at(0)=='#') { QStringList lst =line.remove(0,1).split(':', QString::SkipEmptyParts); //if size is < 2 is a comentary not parameter if (lst.size()<2) continue; QString identifier = lst.at(0).trimmed(); QString value = lst.at(1).trimmed(); if (identifier.toLower()=="letterspacing") { letterSpacing = value.toDouble(); } else if (identifier.toLower()=="wordspacing") { wordSpacing = value.toDouble(); } else if (identifier.toLower()=="linespacingfactor") { lineSpacingFactor = value.toDouble(); } else if (identifier.toLower()=="author") { authors.append(value); } else if (identifier.toLower()=="name") { names.append(value); } else if (identifier.toLower()=="license") { fileLicense = value; } else if (identifier.toLower()=="encoding") { ts.setCodec(QTextCodec::codecForName(value.toLatin1())); encoding = value; } } // Add another letter to this font: else if (line.at(0)=='[') { // uniode character: QChar ch; // read unicode: QRegExp regexp("[0-9A-Fa-f]{4,4}"); regexp.indexIn(line); QString cap = regexp.cap(); if (!cap.isNull()) { int uCode = cap.toInt(NULL, 16); ch = QChar(uCode); } // only unicode allowed else { continue; } // create new letter: RS_FontChar* letter = new RS_FontChar(NULL, ch, RS_Vector(0.0, 0.0)); // Read entities of this letter: QStringList vertex; QStringList coords; do { line = ts.readLine(); if (line.isEmpty()) { continue; } // Defined char: if (line.at(0)=='C') { line.remove(0,1); int uCode = line.toInt(NULL, 16); QChar ch = QChar(uCode); RS_Block* bk = letterList.find(ch); if (bk != NULL) { RS_Entity* bk2 = bk->clone(); bk2->setPen(RS_Pen(RS2::FlagInvalid)); bk2->setLayer(NULL); letter->addEntity(bk2); } } //sequence: else { vertex = line.split(';', QString::SkipEmptyParts); //at least is required two vertex if (vertex.size()<2) continue; RS_Polyline* pline = new RS_Polyline(letter, RS_PolylineData()); pline->setPen(RS_Pen(RS2::FlagInvalid)); pline->setLayer(NULL); for (int i = 0; i < vertex.size(); ++i) { double x1, y1; double bulge = 0; coords = vertex.at(i).split(',', QString::SkipEmptyParts); //at least X,Y is required if (coords.size()<2) continue; x1 = coords.at(0).toDouble(); y1 = coords.at(1).toDouble(); //check presence of bulge if (coords.size() == 3 && coords.at(2).at(0) == QChar('A')){ QString bulgeStr = coords.at(2); bulge = bulgeStr.remove(0,1).toDouble(); pline->setNextBulge(bulge); } pline->addVertex(RS_Vector(x1, y1), bulge); } letter->addEntity(pline); } } while (!line.isEmpty()); letter->calculateBorders(); letterList.add(letter); } } f.close(); }
// setup the preprocessor // code provided by Reginald Stadlbauer <*****@*****.**> void setup() { QString kdedir = getenv( "KDEDIR" ); if ( !kdedir.isNull() ) addIncludePath( kdedir + "/include" ); QString qtdir = getenv( "QTDIR" ); if ( !qtdir.isNull() ) addIncludePath( qtdir + "/include" ); QString qmakespec = getenv( "QMAKESPEC" ); if ( qmakespec.isNull() ) qmakespec = "linux-g++"; // #### implement other mkspecs and find a better way to find the // #### proper mkspec (althoigh this will be no fun :-) addIncludePath( qtdir + "/mkspecs/" + qmakespec ); if ( qmakespec == "linux-g++" ) { addIncludePath( "/include" ); addIncludePath( "/usr/include" ); addIncludePath( "/ust/local/include" ); bool ok; QString gccLibPath = SetupHelper::getGccIncludePath(&ok); if (!ok) return; gccLibPath = gccLibPath.replace( QRegExp( "[\r\n]" ), "" ); addIncludePath( gccLibPath ); addIncludePath( "/usr/include/g++-3" ); addIncludePath( "/usr/include/g++" ); QStringList lines = SetupHelper::getGccMacros(&ok); if (!ok) return; for (QStringList::ConstIterator it = lines.constBegin(); it != lines.constEnd(); ++it) { QStringList lst = QStringList::split( ' ', *it ); if ( lst.count() != 3 ) continue; addMacro( Macro( lst[1], lst[2] ) ); } addMacro( Macro( "__cplusplus", "1" ) ); QString incl = getenv( "INCLUDE" ); QStringList includePaths = QStringList::split( ':', incl ); QStringList::Iterator it = includePaths.begin(); while ( it != includePaths.end() ) { addIncludePath( ( *it ).stripWhiteSpace() ); ++it; } } else if ( qmakespec == "win32-borland" ) { QString incl = getenv( "INCLUDE" ); QStringList includePaths = QStringList::split( ';', incl ); QStringList::Iterator it = includePaths.begin(); while ( it != includePaths.end() ) { addIncludePath( ( *it ).stripWhiteSpace() ); ++it; } // ### I am sure there are more standard include paths on // ### windows. I will fix that soon // ### Also do the compiler specific defines on windows } }
QString UrlBuilder::getSubscriptionsUrl( const QString& username, const QString& device, UrlBuilder::Format f) { QString deviceString = device.isNull() ? QString(QLatin1String("")) : (QLatin1String( "/" ) % device); return s_server % QLatin1String( "/subscriptions/" ) % username % deviceString % getFormatExtension( f ); }
CC_FILE_ERROR PTXFilter::loadFile( QString filename, ccHObject& container, LoadParameters& parameters) { //open ASCII file for reading QFile file(filename); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return CC_FERR_READING; QTextStream inFile(&file); //by default we don't compute normals without asking the user bool computeNormals = (parameters.autoComputeNormals == ccGriddedTools::ALWAYS); CCVector3d PshiftTrans(0,0,0); CCVector3d PshiftCloud(0,0,0); CC_FILE_ERROR result = CC_FERR_NO_LOAD; ScalarType minIntensity = 0; ScalarType maxIntensity = 0; for (unsigned cloudIndex = 0; result == CC_FERR_NO_ERROR || result == CC_FERR_NO_LOAD; cloudIndex++) { unsigned width = 0, height = 0; ccGLMatrixd sensorTransD, cloudTransD; //read header { QString line = inFile.readLine(); if (line.isNull() && container.getChildrenNumber() != 0) //end of file? break; //read the width (number of columns) and the height (number of rows) on the two first lines //(DGM: we transpose the matrix right away) bool ok; height = line.toUInt(&ok); if (!ok) return CC_FERR_MALFORMED_FILE; line = inFile.readLine(); width = line.toUInt(&ok); if (!ok) return CC_FERR_MALFORMED_FILE; ccLog::Print(QString("[PTX] Scan #%1 - grid size: %2 x %3").arg(cloudIndex+1).arg(height).arg(width)); //read sensor transformation matrix for (int i=0; i<4; ++i) { line = inFile.readLine(); QStringList tokens = line.split(" ",QString::SkipEmptyParts); if (tokens.size() != 3) return CC_FERR_MALFORMED_FILE; double* colDest = 0; if (i == 0) { //Translation colDest = sensorTransD.getTranslation(); } else { //X, Y and Z axis colDest = sensorTransD.getColumn(i-1); } for (int j=0; j<3; ++j) { assert(colDest); colDest[j] = tokens[j].toDouble(&ok); if (!ok) return CC_FERR_MALFORMED_FILE; } } //make the transform a little bit cleaner (necessary as it's read from ASCII!) CleanMatrix(sensorTransD); //read cloud transformation matrix for (int i=0; i<4; ++i) { line = inFile.readLine(); QStringList tokens = line.split(" ",QString::SkipEmptyParts); if (tokens.size() != 4) return CC_FERR_MALFORMED_FILE; double* col = cloudTransD.getColumn(i); for (int j=0; j<4; ++j) { col[j] = tokens[j].toDouble(&ok); if (!ok) return CC_FERR_MALFORMED_FILE; } } //make the transform a little bit cleaner (necessary as it's read from ASCII!) CleanMatrix(cloudTransD); //handle Global Shift directly on the first cloud's translation! if (cloudIndex == 0) { if (HandleGlobalShift(cloudTransD.getTranslationAsVec3D(),PshiftTrans,parameters)) { ccLog::Warning("[PTXFilter::loadFile] Cloud has be recentered! Translation: (%.2f,%.2f,%.2f)",PshiftTrans.x,PshiftTrans.y,PshiftTrans.z); } } //'remove' global shift from the sensor and cloud transformation matrices cloudTransD.setTranslation(cloudTransD.getTranslationAsVec3D() + PshiftTrans); sensorTransD.setTranslation(sensorTransD.getTranslationAsVec3D() + PshiftTrans); } //now we can read the grid cells ccPointCloud* cloud = new ccPointCloud(); if (container.getChildrenNumber() == 0) { cloud->setName("unnamed - Cloud"); } else { if (container.getChildrenNumber() == 1) container.getChild(0)->setName("unnamed - Cloud 1"); //update previous cloud name! cloud->setName(QString("unnamed - Cloud %1").arg(container.getChildrenNumber()+1)); } unsigned gridSize = width * height; if (!cloud->reserve(gridSize)) { result = CC_FERR_NOT_ENOUGH_MEMORY; delete cloud; cloud = 0; break; } //set global shift cloud->setGlobalShift(PshiftTrans); //intensities ccScalarField* intensitySF = new ccScalarField(CC_PTX_INTENSITY_FIELD_NAME); if (!intensitySF->reserve(static_cast<unsigned>(gridSize))) { ccLog::Warning("[PTX] Not enough memory to load intensities!"); intensitySF->release(); intensitySF = 0; } //grid for computing normals std::vector<int> indexGrid; bool hasIndexGrid = true; try { indexGrid.resize(gridSize,-1); } catch (const std::bad_alloc&) { ccLog::Warning("[PTX] Not enough memory to save grid structure (required to compute normals!)"); hasIndexGrid = false; } //read points { //progress dialog ccProgressDialog pdlg(true); CCLib::NormalizedProgress nprogress(&pdlg,gridSize); pdlg.setMethodTitle("Loading PTX file"); pdlg.setInfo(qPrintable(QString("Number of cells: %1").arg(gridSize))); pdlg.start(); bool firstPoint = true; bool hasColors = false; bool loadColors = false; int* _indexGrid = hasIndexGrid ? &(indexGrid[0]) : 0; for (unsigned j=0; j<height; ++j) { for (unsigned i=0; i<width; ++i, ++_indexGrid) { QString line = inFile.readLine(); QStringList tokens = line.split(" ",QString::SkipEmptyParts); if (firstPoint) { hasColors = (tokens.size() == 7); if (hasColors) { loadColors = cloud->reserveTheRGBTable(); if (!loadColors) ccLog::Warning("[PTX] Not enough memory to load RGB colors!"); } } if ((hasColors && tokens.size() != 7) || (!hasColors && tokens.size() != 4)) { result = CC_FERR_MALFORMED_FILE; //early stop j = height; break; } double values[4]; for (int v=0; v<4; ++v) { bool ok; values[v] = tokens[v].toDouble(&ok); if (!ok) { result = CC_FERR_MALFORMED_FILE; //early stop j = height; break; } } //we skip "empty" cells if (CCVector3d::fromArray(values).norm2() != 0) { const double* Pd = values; //first point: check for 'big' coordinates if (firstPoint) { if (cloudIndex == 0 && !cloud->isShifted()) //in case the trans. matrix was ok! { CCVector3d P(Pd); if (HandleGlobalShift(P,PshiftCloud,parameters)) { cloud->setGlobalShift(PshiftCloud); ccLog::Warning("[PTXFilter::loadFile] Cloud has been recentered! Translation: (%.2f,%.2f,%.2f)",PshiftCloud.x,PshiftCloud.y,PshiftCloud.z); } } firstPoint = false; } //update index grid if (hasIndexGrid) *_indexGrid = static_cast<int>(cloud->size()); // = index (default value = -1, means no point) //add point cloud->addPoint(CCVector3( static_cast<PointCoordinateType>(Pd[0] + PshiftCloud.x), static_cast<PointCoordinateType>(Pd[1] + PshiftCloud.y), static_cast<PointCoordinateType>(Pd[2] + PshiftCloud.z)) ); //add intensity if (intensitySF) intensitySF->addElement(static_cast<ScalarType>(values[3])); //color if (loadColors) { colorType rgb[3]; for (int c=0; c<3; ++c) { bool ok; unsigned temp = tokens[4+c].toUInt(&ok); ok &= (temp <= static_cast<unsigned>(ccColor::MAX)); if (ok) { rgb[c] = static_cast<colorType>(temp); } else { result = CC_FERR_MALFORMED_FILE; //early stop j = height; break; } } cloud->addRGBColor(rgb); } } if (!nprogress.oneStep()) { result = CC_FERR_CANCELED_BY_USER; break; } } } } //is there at least one valid point in this grid? if (cloud->size() == 0) { delete cloud; cloud = 0; if (intensitySF) intensitySF->release(); ccLog::Warning(QString("[PTX] Scan #%1 is empty?!").arg(cloudIndex+1)); } else { if (result == CC_FERR_NO_LOAD) result = CC_FERR_NO_ERROR; //to make clear that we have loaded at least something! cloud->resize(cloud->size()); if (intensitySF) { assert(intensitySF->currentSize() == cloud->size()); intensitySF->resize(cloud->size()); intensitySF->computeMinAndMax(); int intensitySFIndex = cloud->addScalarField(intensitySF); //keep track of the min and max intensity if (container.getChildrenNumber() == 0) { minIntensity = intensitySF->getMin(); maxIntensity = intensitySF->getMax(); } else { minIntensity = std::min(minIntensity,intensitySF->getMin()); maxIntensity = std::max(maxIntensity,intensitySF->getMax()); } cloud->showSF(true); cloud->setCurrentDisplayedScalarField(intensitySFIndex); } ccGBLSensor* sensor = 0; if (hasIndexGrid && result != CC_FERR_CANCELED_BY_USER) { //determine best sensor parameters (mainly yaw and pitch steps) ccGLMatrix cloudToSensorTrans((sensorTransD.inverse() * cloudTransD).data()); sensor = ccGriddedTools::ComputeBestSensor(cloud,indexGrid,width,height,&cloudToSensorTrans); #ifndef _DEBUG if (cloudIndex == 0) { //shall we ask the user if he wants to compute normals or not? computeNormals = ccGriddedTools::HandleAutoComputeNormalsFeature(parameters.autoComputeNormals); } #endif if (computeNormals) { //try to compute normals bool canceledByUser = false; if (!ccGriddedTools::ComputeNormals(cloud,indexGrid,static_cast<int>(width),static_cast<int>(height),&canceledByUser)) { if (canceledByUser) { //if the user cancelled the normal process, we cancel everything! result = CC_FERR_CANCELED_BY_USER; } else { computeNormals = false; } } } } //don't need it anymore indexGrid.clear(); //we apply the transformation ccGLMatrix cloudTrans(cloudTransD.data()); cloud->applyGLTransformation_recursive(&cloudTrans); if (sensor) { ccGLMatrix sensorTrans(sensorTransD.data()); sensor->setRigidTransformation(sensorTrans); //after cloud->applyGLTransformation_recursive! cloud->addChild(sensor); } cloud->setVisible(true); cloud->showColors(cloud->hasColors()); cloud->showNormals(cloud->hasNormals()); container.addChild(cloud); #ifdef _DEBUG //break; #endif } } //update scalar fields saturation (globally!) { bool validIntensityRange = true; if (minIntensity < 0 || maxIntensity > 1.0) { ccLog::Warning("[PTX] Intensity values are invalid (they should all fall in [0 ; 1])"); validIntensityRange = false; } for (unsigned i=0; i<container.getChildrenNumber(); ++i) { ccHObject* obj = container.getChild(i); assert(obj && obj->isA(CC_TYPES::POINT_CLOUD)); CCLib::ScalarField* sf = static_cast<ccPointCloud*>(obj)->getScalarField(0); if (sf) { ccScalarField* ccSF = static_cast<ccScalarField*>(sf); ccSF->setColorScale(ccColorScalesManager::GetDefaultScale(validIntensityRange ? ccColorScalesManager::ABS_NORM_GREY : ccColorScalesManager::GREY)); ccSF->setSaturationStart(0/*minIntensity*/); ccSF->setSaturationStop(maxIntensity); } } } return result; }
void toNewConnection::changeProvider(int current) { try { QString provider = getCurrentProvider(); if (provider.isNull() || provider.isEmpty()) return; bool oldStateH = Host->blockSignals(true); Host->clear(); QList<QString> hosts = toConnectionProviderRegistrySing::Instance().get(provider).hosts(); DefaultPort = 0; foreach(QString const & host, hosts) { if (host.isEmpty()) continue; else if (host.startsWith(":")) DefaultPort = host.mid(1).toInt(); else Host->addItem(host); // This might also call changeHost(), unless blockSignals == true } Host->blockSignals(oldStateH); Database->clear(); changeHost(); // will populate Databases combobox // seems i broke this for oracle if (!DefaultPort) { if (provider.startsWith("Oracle")) DefaultPort = 1521; } if (Provider->currentText().startsWith("Oracle")) // TODO add provider property { SchemaLabel->show(); Schema->show(); } else { SchemaLabel->hide(); Schema->hide(); } Port->setValue(DefaultPort); if (Provider->currentText().startsWith(ORACLE_TNSCLIENT) || getCurrentProvider() == "QODBC") { HostLabel->hide(); Host->hide(); PortLabel->hide(); Port->hide(); } else { HostLabel->show(); Host->show(); PortLabel->show(); Port->show(); } QList<QWidget *> widgets = OptionGroup->findChildren<QWidget *>(); foreach(QWidget * w, widgets) delete w; QList<QString> options = toConnectionProviderRegistrySing::Instance().get(provider).options(); foreach(QString option, options) { if (option == "-") continue; bool defOn = false; if (option.startsWith("*")) { defOn = true; option = option.mid(1); } QCheckBox *ow = new QCheckBox(OptionGroup); ow->setText(option); ow->setChecked(defOn); OptionGroup->layout()->addWidget(ow); ow->show(); } if (options.empty()) OptionGroup->hide(); else OptionGroup->show(); } catch (const QString &str) { Utils::toStatusMessage(str); } }
bool AddDeviceOperation::setArguments(const QStringList &args) { m_authentication = -1; m_origin = 1; m_sshPort = 0; m_timeout = 5; m_type = -1; m_version = 0; for (int i = 0; i < args.count(); ++i) { const QString current = args.at(i); const QString next = ((i + 1) < args.count()) ? args.at(i + 1) : QString(); if (current == QLatin1String("--id")) { if (next.isNull()) return false; ++i; // skip next; m_id = next; continue; } if (current == QLatin1String("--name")) { if (next.isNull()) return false; ++i; // skip next; m_displayName = next; continue; } if (current == QLatin1String("--authentication")) { if (next.isNull()) return false; ++i; // skip next; bool ok; m_authentication = next.toInt(&ok); if (!ok) return false; continue; } if (current == QLatin1String("--b2qHardware")) { if (next.isNull()) return false; ++i; // skip next; m_b2q_platformHardware = next; continue; } if (current == QLatin1String("--b2qSoftware")) { if (next.isNull()) return false; ++i; // skip next; m_b2q_platformSoftware = next; continue; } if (current == QLatin1String("--freePorts")) { if (next.isNull()) return false; ++i; // skip next; m_freePortsSpec = next; continue; } if (current == QLatin1String("--host")) { if (next.isNull()) return false; ++i; // skip next; m_host = next; continue; } if (current == QLatin1String("--debugServerKey")) { if (next.isNull()) return false; ++i; // skip next; m_debugServer = next; continue; } if (current == QLatin1String("--keyFile")) { if (next.isNull()) return false; ++i; // skip next; m_keyFile = next; continue; } if (current == QLatin1String("--origin")) { if (next.isNull()) return false; ++i; // skip next; bool ok; m_origin = next.toInt(&ok); if (!ok) return false; continue; } if (current == QLatin1String("--osType")) { if (next.isNull()) return false; ++i; // skip next; m_osType = next; continue; } if (current == QLatin1String("--password")) { if (next.isNull()) return false; ++i; // skip next; m_password = next; continue; } if (current == QLatin1String("--sshPort")) { if (next.isNull()) return false; ++i; // skip next; bool ok; m_sshPort = next.toInt(&ok); if (!ok) return false; continue; } if (current == QLatin1String("--timeout")) { if (next.isNull()) return false; ++i; // skip next; bool ok; m_timeout = next.toInt(&ok); if (!ok) return false; continue; } if (current == QLatin1String("--type")) { if (next.isNull()) return false; ++i; // skip next; bool ok; m_type = next.toInt(&ok); if (!ok) return false; continue; } if (current == QLatin1String("--uname")) { if (next.isNull()) return false; ++i; // skip next; m_uname = next; continue; } if (next.isNull()) return false; ++i; // skip next; KeyValuePair pair(current, next); if (!pair.value.isValid()) return false; m_extra << pair; } if (m_id.isEmpty()) std::cerr << "No id given for device." << std::endl << std::endl; if (m_displayName.isEmpty()) std::cerr << "No name given for device." << std::endl << std::endl; return !m_id.isEmpty() && !m_displayName.isEmpty() && m_type >= 0; }
Note* NoteFactory::dropNote(const QMimeData *source, Basket *parent, bool fromDrop, Qt::DropAction action, Note */*noteSource*/) { Note *note = 0L; QStringList formats = source->formats(); /* No data */ if (formats.size() == 0) { // TODO: add a parameter to say if it's from a clipboard paste, a selection paste, or a drop // To be able to say "The clipboard/selection/drop is empty". // KMessageBox::error(parent, i18n("There is no data to insert."), i18n("No Data")); return 0; } /* Debug */ if (Global::debugWindow) { *Global::debugWindow << "<b>Drop :</b>"; for (int i = 0; formats.size(); ++i) *Global::debugWindow << "\t[" + QString::number(i) + "] " + formats[i]; switch (action) { // The source want that we: case Qt::CopyAction: *Global::debugWindow << ">> Drop action: Copy"; break; case Qt::MoveAction: *Global::debugWindow << ">> Drop action: Move"; break; case Qt::LinkAction: *Global::debugWindow << ">> Drop action: Link"; break; default: *Global::debugWindow << ">> Drop action: Unknown"; // supported by Qt! } } /* Copy or move a Note */ if (NoteDrag::canDecode(source)) { bool moveFiles = fromDrop && action == Qt::MoveAction; bool moveNotes = moveFiles; return NoteDrag::decode(source, parent, moveFiles, moveNotes); // Filename will be kept } /* Else : Drop object to note */ QImage image = qvariant_cast<QImage>(source->imageData()) ; if ( !image.isNull() ) return createNoteImage(QPixmap::fromImage(image), parent); if (source->hasColor()){ return createNoteColor(qvariant_cast<QColor>(source->colorData()), parent); } // And then the hack (if provide color MIME type or a text that contains color), using createNote Color RegExp: QString hack; QRegExp exp("^#(?:[a-fA-F\\d]{3}){1,4}$"); hack = source->text(); if (source->hasFormat("application/x-color") || (!hack.isNull() && exp.exactMatch(hack)) ) { QColor color = qvariant_cast<QColor>(source->colorData()) ; if (color.isValid()) return createNoteColor(color, parent); // if ( (note = createNoteColor(color, parent)) ) // return note; // // Theorically it should be returned. If not, continue by dropping other things } KUrl::List urls = KUrl::List::fromMimeData(source); if ( !urls.isEmpty() ){ // If it's a Paste, we should know if files should be copied (copy&paste) or moved (cut&paste): if (!fromDrop && Tools::isAFileCut(source)) action = Qt::MoveAction; return dropURLs(urls, parent, action, fromDrop); } // FIXME: use dropURLs() also from Mozilla? /* * Mozilla's stuff sometimes uses utf-16-le - little-endian UTF-16. * * This has the property that for the ASCII subset case (And indeed, the * ISO-8859-1 subset, I think), if you treat it as a C-style string, * it'll come out to one character long in most cases, since it looks * like: * * "<\0H\0T\0M\0L\0>\0" * * A strlen() call on that will give you 1, which simply isn't correct. * That might, I suppose, be the answer, or something close. * * Also, Mozilla's drag/drop code predates the use of MIME types in XDnD * - hence it'll throw about STRING and UTF8_STRING quite happily, hence * the odd named types. * * Thanks to Dave Cridland for having said me that. */ if (source->hasFormat("text/x-moz-url")) { // FOR MOZILLA // Get the array and create a QChar array of 1/2 of the size QByteArray mozilla = source->data("text/x-moz-url"); QVector<QChar> chars( mozilla.count() / 2 ); // A small debug work to know the value of each bytes if (Global::debugWindow) for (int i = 0; i < mozilla.count(); i++) *Global::debugWindow << QString("'") + QChar(mozilla[i]) + "' " + QString::number(int(mozilla[i])); // text/x-moz-url give the URL followed by the link title and separed by OxOA (10 decimal: new line?) uint size = 0; QChar *name = 0L; // For each little endian mozilla chars, copy it to the array of QChars for (int i = 0; i < mozilla.count(); i += 2) { chars[i/2] = QChar(mozilla[i], mozilla[i+1]); if (mozilla.at(i) == 0x0A) { size = i/2; name = &(chars[i/2+1]); } } // Create a QString that take the address of the first QChar and a length if (name == 0L) { // We haven't found name (FIXME: Is it possible ?) QString normalHtml(&(chars[0]), chars.size()); return createNoteLink(normalHtml, parent); } else { QString normalHtml( &(chars[0]), size ); QString normalTitle( name, chars.size()-size-1); return createNoteLink(normalHtml, normalTitle, parent); } } if (source->hasFormat("text/html")) { QString html; QString subtype("html"); // If the text/html comes from Mozilla or GNOME it can be UTF-16 encoded: we need ExtendedTextDrag to check that ExtendedTextDrag::decode(source, html, subtype); return createNoteHtml(html, parent); } QString text; // If the text/plain comes from GEdit or GNOME it can be empty: we need ExtendedTextDrag to check other MIME types if ( ExtendedTextDrag::decode(source, text) ) return createNoteFromText(text, parent); /* Unsucceful drop */ note = createNoteUnknown(source, parent); QString message = i18n("<p>%1 doesn't support the data you've dropped.<br>" "It however created a generic note, allowing you to drag or copy it to an application that understand it.</p>" "<p>If you want the support of these data, please contact developer or visit the " "<a href=\"http://basket.kde.org/dropdb.php\">BasKet Drop Database</a>.</p>",KGlobal::mainComponent().aboutData()->programName()); KMessageBox::information(parent, message, i18n("Unsupported MIME Type(s)"), "unsupportedDropInfo", KMessageBox::AllowLink); return note; }
/** \brief Downloads a QNetworkRequest via the QNetworkAccessManager * \param dlInfo MythDownloadInfo information for download */ void MythDownloadManager::downloadQNetworkRequest(MythDownloadInfo *dlInfo) { if (!dlInfo) return; static const char dateFormat[] = "ddd, dd MMM yyyy hh:mm:ss 'GMT'"; QUrl qurl(dlInfo->m_url); QNetworkRequest request; if (dlInfo->m_request) { request = *dlInfo->m_request; delete dlInfo->m_request; dlInfo->m_request = NULL; } else request.setUrl(qurl); if (!dlInfo->m_reload) { // Prefer the in-cache item if one exists and it is less than 5 minutes // old and it will not expire in the next 10 seconds QDateTime now = MythDate::current(); // Handle redirects, we want the metadata of the file headers QString redirectLoc; int limit = 0; while (!(redirectLoc = getHeader(qurl, "Location")).isNull()) { if (limit == CACHE_REDIRECTION_LIMIT) { LOG(VB_GENERAL, LOG_WARNING, QString("Cache Redirection limit " "reached for %1") .arg(qurl.toString())); return; } qurl.setUrl(redirectLoc); limit++; } LOG(VB_NETWORK, LOG_DEBUG, QString("Checking cache for %1") .arg(qurl.toString())); m_infoLock->lock(); QNetworkCacheMetaData urlData = m_manager->cache()->metaData(qurl); m_infoLock->unlock(); if ((urlData.isValid()) && ((!urlData.expirationDate().isValid()) || (QDateTime(urlData.expirationDate().toUTC()).secsTo(now) < 10))) { QString dateString = getHeader(urlData, "Date"); if (!dateString.isNull()) { QDateTime loadDate = MythDate::fromString(dateString, dateFormat); loadDate.setTimeSpec(Qt::UTC); if (loadDate.secsTo(now) <= 720) { dlInfo->m_preferCache = true; LOG(VB_NETWORK, LOG_DEBUG, QString("Preferring cache for %1") .arg(qurl.toString())); } } } } if (dlInfo->m_preferCache) request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); request.setRawHeader("User-Agent", "MythTV v" MYTH_BINARY_VERSION " MythDownloadManager"); if (dlInfo->m_headers) { QHash<QByteArray, QByteArray>::const_iterator it = dlInfo->m_headers->constBegin(); for ( ; it != dlInfo->m_headers->constEnd(); ++it ) { if (!it.key().isEmpty() && !it.value().isEmpty()) { request.setRawHeader(it.key(), it.value()); } } } switch (dlInfo->m_requestType) { case kRequestPost : dlInfo->m_reply = m_manager->post(request, *dlInfo->m_data); break; case kRequestHead : dlInfo->m_reply = m_manager->head(request); break; case kRequestGet : default: dlInfo->m_reply = m_manager->get(request); break; } m_downloadReplies[dlInfo->m_reply] = dlInfo; if (dlInfo->m_authCallback) { connect(m_manager, SIGNAL(authenticationRequired(QNetworkReply *, QAuthenticator *)), this, SLOT(authCallback(QNetworkReply *, QAuthenticator *))); }
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice, const QString &fname, QString currentPath, bool ignoreErrors) { Q_ASSERT(m_errorDevice); const QChar slash = QLatin1Char('/'); if (!currentPath.isEmpty() && !currentPath.endsWith(slash)) currentPath += slash; QXmlStreamReader reader(inputDevice); QStack<RCCXmlTag> tokens; QString prefix; QLocale::Language language = QLocale::c().language(); QLocale::Country country = QLocale::c().country(); QString alias; int compressLevel = m_compressLevel; int compressThreshold = m_compressThreshold; while (!reader.atEnd()) { QXmlStreamReader::TokenType t = reader.readNext(); switch (t) { case QXmlStreamReader::StartElement: if (reader.name() == m_strings.TAG_RCC) { if (!tokens.isEmpty()) reader.raiseError(QLatin1String("expected <RCC> tag")); else tokens.push(RccTag); } else if (reader.name() == m_strings.TAG_RESOURCE) { if (tokens.isEmpty() || tokens.top() != RccTag) { reader.raiseError(QLatin1String("unexpected <RESOURCE> tag")); } else { tokens.push(ResourceTag); QXmlStreamAttributes attributes = reader.attributes(); language = QLocale::c().language(); country = QLocale::c().country(); if (attributes.hasAttribute(m_strings.ATTRIBUTE_LANG)) { QString attribute = attributes.value(m_strings.ATTRIBUTE_LANG).toString(); QLocale lang = QLocale(attribute); language = lang.language(); if (2 == attribute.length()) { // Language only country = QLocale::AnyCountry; } else { country = lang.country(); } } prefix.clear(); if (attributes.hasAttribute(m_strings.ATTRIBUTE_PREFIX)) prefix = attributes.value(m_strings.ATTRIBUTE_PREFIX).toString(); if (!prefix.startsWith(slash)) prefix.prepend(slash); if (!prefix.endsWith(slash)) prefix += slash; } } else if (reader.name() == m_strings.TAG_FILE) { if (tokens.isEmpty() || tokens.top() != ResourceTag) { reader.raiseError(QLatin1String("unexpected <FILE> tag")); } else { tokens.push(FileTag); QXmlStreamAttributes attributes = reader.attributes(); alias.clear(); if (attributes.hasAttribute(m_strings.ATTRIBUTE_ALIAS)) alias = attributes.value(m_strings.ATTRIBUTE_ALIAS).toString(); compressLevel = m_compressLevel; if (attributes.hasAttribute(m_strings.ATTRIBUTE_COMPRESS)) compressLevel = attributes.value(m_strings.ATTRIBUTE_COMPRESS).toString().toInt(); compressThreshold = m_compressThreshold; if (attributes.hasAttribute(m_strings.ATTRIBUTE_THRESHOLD)) compressThreshold = attributes.value(m_strings.ATTRIBUTE_THRESHOLD).toString().toInt(); // Special case for -no-compress. Overrides all other settings. if (m_compressLevel == -2) compressLevel = 0; } } else { reader.raiseError(QString(QLatin1String("unexpected tag: %1")).arg(reader.name().toString())); } break; case QXmlStreamReader::EndElement: if (reader.name() == m_strings.TAG_RCC) { if (!tokens.isEmpty() && tokens.top() == RccTag) tokens.pop(); else reader.raiseError(QLatin1String("unexpected closing tag")); } else if (reader.name() == m_strings.TAG_RESOURCE) { if (!tokens.isEmpty() && tokens.top() == ResourceTag) tokens.pop(); else reader.raiseError(QLatin1String("unexpected closing tag")); } else if (reader.name() == m_strings.TAG_FILE) { if (!tokens.isEmpty() && tokens.top() == FileTag) tokens.pop(); else reader.raiseError(QLatin1String("unexpected closing tag")); } break; case QXmlStreamReader::Characters: if (reader.isWhitespace()) break; if (tokens.isEmpty() || tokens.top() != FileTag) { reader.raiseError(QLatin1String("unexpected text")); } else { QString fileName = reader.text().toString(); if (fileName.isEmpty()) { const QString msg = QString::fromLatin1("RCC: Warning: Null node in XML of '%1'\n").arg(fname); m_errorDevice->write(msg.toUtf8()); } if (alias.isNull()) alias = fileName; alias = QDir::cleanPath(alias); while (alias.startsWith(QLatin1String("../"))) alias.remove(0, 3); alias = QDir::cleanPath(m_resourceRoot) + prefix + alias; QString absFileName = fileName; if (QDir::isRelativePath(absFileName)) absFileName.prepend(currentPath); QFileInfo file(absFileName); if (!file.exists()) { m_failedResources.push_back(absFileName); const QString msg = QString::fromLatin1("RCC: Error in '%1': Cannot find file '%2'\n").arg(fname).arg(fileName); m_errorDevice->write(msg.toUtf8()); if (ignoreErrors) continue; else return false; } else if (file.isFile()) { const bool arc = addFile(alias, RCCFileInfo(alias.section(slash, -1), file, language, country, RCCFileInfo::NoFlags, compressLevel, compressThreshold) ); if (!arc) m_failedResources.push_back(absFileName); } else { QDir dir; if (file.isDir()) { dir.setPath(file.filePath()); } else { dir.setPath(file.path()); dir.setNameFilters(QStringList(file.fileName())); if (alias.endsWith(file.fileName())) alias = alias.left(alias.length()-file.fileName().length()); } if (!alias.endsWith(slash)) alias += slash; QDirIterator it(dir, QDirIterator::FollowSymlinks|QDirIterator::Subdirectories); while (it.hasNext()) { it.next(); QFileInfo child(it.fileInfo()); if (child.fileName() != QLatin1String(".") && child.fileName() != QLatin1String("..")) { const bool arc = addFile(alias + child.fileName(), RCCFileInfo(child.fileName(), child, language, country, child.isDir() ? RCCFileInfo::Directory : RCCFileInfo::NoFlags, compressLevel, compressThreshold) ); if (!arc) m_failedResources.push_back(child.fileName()); } } } } break; default: break; } } if (reader.hasError()) { if (ignoreErrors) return true; int errorLine = reader.lineNumber(); int errorColumn = reader.columnNumber(); QString errorMessage = reader.errorString(); QString msg = QString::fromLatin1("RCC Parse Error: '%1' Line: %2 Column: %3 [%4]\n").arg(fname).arg(errorLine).arg(errorColumn).arg(errorMessage); m_errorDevice->write(msg.toUtf8()); return false; } if (m_root == 0) { const QString msg = QString::fromUtf8("RCC: Warning: No resources in '%1'.\n").arg(fname); m_errorDevice->write(msg.toUtf8()); if (!ignoreErrors && m_format == Binary) { // create dummy entry, otherwise loading with QResource will crash m_root = new RCCFileInfo(QString(), QFileInfo(), QLocale::C, QLocale::AnyCountry, RCCFileInfo::Directory); } } return true; }
int Option::parseCommandLine(QStringList &args, QMakeCmdLineParserState &state) { enum { ArgNone, ArgOutput } argState = ArgNone; int x = 0; while (x < args.count()) { switch (argState) { case ArgOutput: Option::output.setFileName(args.at(x--)); args.erase(args.begin() + x, args.begin() + x + 2); argState = ArgNone; continue; default: QMakeGlobals::ArgumentReturn cmdRet = globals->addCommandLineArguments(state, args, &x); if (cmdRet == QMakeGlobals::ArgumentsOk) break; if (cmdRet == QMakeGlobals::ArgumentMalformed) { fprintf(stderr, "***Option %s requires a parameter\n", qPrintable(args.at(x - 1))); return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } Q_ASSERT(cmdRet == QMakeGlobals::ArgumentUnknown); QString arg = args.at(x); if (arg.startsWith(QLatin1Char('-'))) { if (arg == "-d") { Option::debug_level++; } else if (arg == "-v" || arg == "-version" || arg == "--version") { fprintf(stdout, "QMake version %s\n" "Using Qt version %s in %s\n", QMAKE_VERSION_STR, QT_VERSION_STR, QLibraryInfo::location(QLibraryInfo::LibrariesPath).toLatin1().constData()); #ifdef QMAKE_OPENSOURCE_VERSION fprintf(stdout, "QMake is Open Source software from Digia Plc and/or its subsidiary(-ies).\n"); #endif return Option::QMAKE_CMDLINE_BAIL; } else if (arg == "-h" || arg == "-help" || arg == "--help") { return Option::QMAKE_CMDLINE_SHOW_USAGE; } else if (arg == "-Wall") { Option::warn_level |= WarnAll; } else if (arg == "-Wparser") { Option::warn_level |= WarnParser; } else if (arg == "-Wlogic") { Option::warn_level |= WarnLogic; } else if (arg == "-Wdeprecated") { Option::warn_level |= WarnDeprecated; } else if (arg == "-Wnone") { Option::warn_level = WarnNone; } else if (arg == "-r" || arg == "-recursive") { Option::recursive = true; args.removeAt(x); continue; } else if (arg == "-nr" || arg == "-norecursive") { Option::recursive = false; args.removeAt(x); continue; } else if (arg == "-o" || arg == "-output") { argState = ArgOutput; } else { if (Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE || Option::qmake_mode == Option::QMAKE_GENERATE_PRL) { if (arg == "-nodepend" || arg == "-nodepends") { Option::mkfile::do_deps = false; } else if (arg == "-nomoc") { Option::mkfile::do_mocs = false; } else if (arg == "-createstub") { Option::mkfile::do_stub_makefile = true; } else if (arg == "-nodependheuristics") { Option::mkfile::do_dep_heuristics = false; } else if (arg == "-E") { Option::mkfile::do_preprocess = true; } else { fprintf(stderr, "***Unknown option %s\n", arg.toLatin1().constData()); return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } } else if (Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT) { if (arg == "-nopwd") { Option::projfile::do_pwd = false; } else { fprintf(stderr, "***Unknown option %s\n", arg.toLatin1().constData()); return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } } } } else { bool handled = true; if(Option::qmake_mode == Option::QMAKE_QUERY_PROPERTY || Option::qmake_mode == Option::QMAKE_SET_PROPERTY || Option::qmake_mode == Option::QMAKE_UNSET_PROPERTY) { Option::prop::properties.append(arg); } else { QFileInfo fi(arg); if(!fi.makeAbsolute()) //strange arg = fi.filePath(); if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE || Option::qmake_mode == Option::QMAKE_GENERATE_PRL) { if(fi.isDir()) { QString proj = detectProjectFile(arg); if (!proj.isNull()) arg = proj; } Option::mkfile::project_files.append(arg); } else if(Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT) { Option::projfile::project_dirs.append(arg); } else { handled = false; } } if(!handled) { return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } args.removeAt(x); continue; } } x++; } if (argState != ArgNone) { fprintf(stderr, "***Option %s requires a parameter\n", qPrintable(args.at(x - 1))); return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } return Option::QMAKE_CMDLINE_SUCCESS; }
void SMCStyleWidget::showColors(const QList<CharStyle*> &cstyles) { strokeShade_->setEnabled(true); strokeColor_->setEnabled(true); double d = -30000; for (int i = 0; i < cstyles.count(); ++i) { if (d != -30000 && cstyles[i]->fillShade() != d) { d = -30000; break; } else d = cstyles[i]->fillShade(); } if (d == -30000) fillShade_->setText( tr("Shade")); else fillShade_->setValue(qRound(d)); d = -30000; for (int i = 0; i < cstyles.count(); ++i) { if (d != -30000 && cstyles[i]->strokeShade() != d) { d = -30000; break; } else d = cstyles[i]->strokeShade(); } if (d == -30000) { strokeShade_->setValue(21); strokeShade_->setText( tr("Shade")); } else strokeShade_->setValue(qRound(d)); QString s; QString emptyString; for (int i = 0; i < cstyles.count(); ++i) { if (!s.isNull() && s != cstyles[i]->fillColor()) { s = emptyString; break; } else s = cstyles[i]->fillColor(); } if (s.isEmpty()) { if (fillColor_->itemText(fillColor_->count() - 1) != "") fillColor_->addItem(""); fillColor_->setCurrentIndex(fillColor_->count() - 1); } else fillColor_->setCurrentText(s); s = emptyString; for (int i = 0; i < cstyles.count(); ++i) { if (!s.isNull() && s != cstyles[i]->strokeColor()) { s = emptyString; break; } else s = cstyles[i]->strokeColor(); } if (s.isEmpty()) { if (strokeColor_->itemText(strokeColor_->count() - 1) != "") strokeColor_->addItem(""); strokeColor_->setCurrentIndex(fillColor_->count() - 1); } else strokeColor_->setCurrentText(s); }
void SceneObject::draw(ShaderStack *stack) { bool shaderOverridden = false; if ( !geometry()->isEmpty() ) { // If we have a shader override, push the override. QString shaderOverrideName = geometry()->shaderOverride(); if ( !shaderOverrideName.isNull() ) { ShaderProgram* program = resourceManager()->shader(shaderOverrideName); if ( program ) { shaderOverridden = true; stack->shaderPush(program); } } } // Multiply the modelWorld matrix by our current one. // This updates the shader uniform too. // We do this even if the geometry is empty, so that the // transformation will apply recursively. // It is the caller's responsibility to manage pushing // and popping of the m2w matrix. stack->modelToWorldPostMultiply(localToParent()); if ( !geometry()->isEmpty() ) { // Upload and bind the geometry. geometry()->upload(); geometry()->bindVertices(true); geometry()->bindIndices(true); // Apply the data format. geometry()->applyDataFormat(stack->shaderTop()); // If we're selected, set the global colour. bool pushedColor = false; MapDocument* doc = m_pScene->document(); if ( doc->selectedSet().contains(this) ) { pushedColor = true; stack->globalColorPush(); stack->globalColorSetTop(doc->selectedColor()); } // Apply the texture. QOpenGLTexture* tex = resourceManager()->texture(geometry()->texture(0)); tex->bind(0); // Draw. geometry()->draw(); if ( pushedColor ) { stack->globalColorPop(); } // Pop the shader if we pushed one earlier. if ( shaderOverridden ) { stack->shaderPop(); } } }