QApplicationActivityObserver * QApplicationActivityObserver::instance()
{
	static QMutex mymutex;
	static QScopedPointer<QApplicationActivityObserver> instance;
	QMutexLocker locker(&mymutex);

	// Creating instance
	if (instance.isNull())
	{
		instance.reset(new QApplicationActivityObserver());
	}

	// Installing event filter
	static bool installed_filter = false;
	if (!installed_filter)
	{
		QCoreApplication * app = QCoreApplication::instance();
		if (app)
		{
			app->installEventFilter(instance.data());
			installed_filter = true;
			qDebug()<<__FUNCTION__<<"Successfully installed event filter.";
		}
		else
		{
			qWarning()<<__FUNCTION__<<"installing event filter failed because QCoreApplication instance doesn't exist, will try later.";
		}
	}

	return instance.data();
}
Exemple #2
0
void Reporter::report(const QString &message, const QScopedPointer<utils::OutFile> &file)
{
	if (!file.isNull()) {
		(*file)() << message;
		file->flush();
	}
}
void tst_QScopedPointer::isNullSignature()
{
    const QScopedPointer<int> p(new int(69));

    /* The signature should be const and return bool. */
    static_cast<bool>(p.isNull());
}
Exemple #4
0
/*
 * Initialize app icon
 */
const QIcon &lamexp_app_icon(void)
{
	QReadLocker readLock(&g_lamexp_icon_lock);

	//Already initialized?
	if(!g_lamexp_icon_data.isNull())
	{
		return *g_lamexp_icon_data;
	}

	readLock.unlock();
	QWriteLocker writeLock(&g_lamexp_icon_lock);

	while(g_lamexp_icon_data.isNull())
	{
		QDate currentDate = QDate::currentDate();
		QTime currentTime = QTime::currentTime();
	
		if(lamexp_thanksgiving(currentDate))
		{
			g_lamexp_icon_data.reset(new QIcon(":/MainIcon6.png"));
		}
		else if(((currentDate.month() == 12) && (currentDate.day() == 31) && (currentTime.hour() >= 20)) || ((currentDate.month() == 1) && (currentDate.day() == 1)  && (currentTime.hour() <= 19)))
		{
			g_lamexp_icon_data.reset(new QIcon(":/MainIcon5.png"));
		}
		else if(((currentDate.month() == 10) && (currentDate.day() == 31) && (currentTime.hour() >= 12)) || ((currentDate.month() == 11) && (currentDate.day() == 1)  && (currentTime.hour() <= 11)))
		{
			g_lamexp_icon_data.reset(new QIcon(":/MainIcon4.png"));
		}
		else if((currentDate.month() == 12) && (currentDate.day() >= 24) && (currentDate.day() <= 26))
		{
			g_lamexp_icon_data.reset(new QIcon(":/MainIcon3.png"));
		}
		else if(lamexp_computus(currentDate))
		{
			g_lamexp_icon_data.reset(new QIcon(":/MainIcon2.png"));
		}
		else
		{
			g_lamexp_icon_data.reset(new QIcon(":/MainIcon1.png"));
		}
	}

	return *g_lamexp_icon_data;
}
quint32 MUtils::Translation::get_country(const QString &langId)
{
	QReadLocker readLockTranslations(&g_translation_lock);
	const QString key = langId.simplified().toLower();
	if(key.isEmpty() || g_translation_data.isNull() || (!g_translation_data->contains(key)))
	{
		return 0;
	}

	return (*g_translation_data)[key].second.second;
}
bool QWindowsInputContext::composition(HWND hwnd, LPARAM lParamIn)
{
    QObject *fo = qApp->focusObject();
    const int lParam = int(lParamIn);
    if (QWindowsContext::verboseInputMethods)
        qDebug() << '>' << __FUNCTION__ << fo << debugComposition(lParam)
                 << " composing=" << m_compositionContext.isComposing;
    if (!fo || m_compositionContext.hwnd != hwnd || !lParam)
        return false;
    const HIMC himc = ImmGetContext(m_compositionContext.hwnd);
    if (!himc)
        return false;

    QScopedPointer<QInputMethodEvent> event;
    if (lParam & (GCS_COMPSTR | GCS_COMPATTR | GCS_CURSORPOS)) {
        if (!m_compositionContext.isComposing)
            startContextComposition();
        // Some intermediate composition result. Parametrize event with
        // attribute sequence specifying the formatting of the converted part.
        int selStart, selLength;
        m_compositionContext.composition = getCompositionString(himc, GCS_COMPSTR);
        m_compositionContext.position = ImmGetCompositionString(himc, GCS_CURSORPOS, 0, 0);
        getCompositionStringConvertedRange(himc, &selStart, &selLength);
        if ((lParam & CS_INSERTCHAR) && (lParam & CS_NOMOVECARET)) {
            // make Korean work correctly. Hope this is correct for all IMEs
            selStart = 0;
            selLength = m_compositionContext.composition.size();
        }
        if (!selLength)
            selStart = 0;

        event.reset(new QInputMethodEvent(m_compositionContext.composition,
                                          intermediateMarkup(m_compositionContext.position,
                                                  m_compositionContext.composition.size(),
                                                  selStart, selLength)));
    }
    if (event.isNull())
        event.reset(new QInputMethodEvent);

    if (lParam & GCS_RESULTSTR) {
        // A fixed result, return the converted string
        event->setCommitString(getCompositionString(himc, GCS_RESULTSTR));
        endContextComposition();
    }
    const bool result = QCoreApplication::sendEvent(fo, event.data());
    if (QWindowsContext::verboseInputMethods)
        qDebug() << '<' << __FUNCTION__ << "sending markup="
                 << event->attributes().size()
                 << " commit=" << event->commitString()
                 << " to " << fo << " returns " << result;
    update(Qt::ImQueryAll);
    ImmReleaseContext(m_compositionContext.hwnd, himc);
    return result;
}
Exemple #7
0
/*
 * Check for tool
 */
bool lamexp_tools_check(const QString &toolName)
{
	QReadLocker readLock(&g_lamexp_tools_lock);

	if(!g_lamexp_tools_data.isNull())
	{
		const QString key = toolName.simplified().toLower();
		return g_lamexp_tools_data->contains(key);
	}

	return false;
}
QString MUtils::Translation::get_name(const QString &langId)
{
	QReadLocker readLockTranslations(&g_translation_lock);

	const QString key = langId.simplified().toLower();
	if(key.isEmpty() || g_translation_data.isNull() || (!g_translation_data->contains(key)))
	{
		return QString();
	}

	return (*g_translation_data)[key].first.first;
}
int MUtils::Translation::enumerate(QStringList &list)
{
	QReadLocker readLockTranslations(&g_translation_lock);

	if(g_translation_data.isNull())
	{
		list.clear();
		return -1;
	}

	list.swap(g_translation_data->keys());
	return list.count();
}
void tst_QScopedPointer::isNull()
{
    /* Invoke on default constructed value. */
    {
        QScopedPointer<int> p;
        QVERIFY(p.isNull());
    }

    /* Invoke on a set value. */
    {
        QScopedPointer<int> p(new int(69));
        QVERIFY(!p.isNull());
    }
}
Exemple #11
0
bool MUtils::Translation::install_translator(const QString &langId)
{
	QReadLocker readLockTranslations(&g_translation_lock);

	const QString key = langId.simplified().toLower();
	if(key.isEmpty() || g_translation_data.isNull() || (!g_translation_data->contains(key)))
	{
		return false;
	}

	const QString qmFile = (*g_translation_data)[key].first.second;
	readLockTranslations.unlock();
	return install_translator_from_file(qmFile);
}
Exemple #12
0
/*
 * Lookup tool path
 */
const QString &lamexp_tools_lookup(const QString &toolName)
{
	QReadLocker readLock(&g_lamexp_tools_lock);

	if(!g_lamexp_tools_data.isNull())
	{
		const QString key = toolName.simplified().toLower();
		if(g_lamexp_tools_data->contains(key))
		{
			return (*g_lamexp_tools_data)[key].first->filePath();
		}
	}

	return g_null_string;
}
Exemple #13
0
/*
 * Clean-up *all* registered tools
 */
static void lamexp_tools_clean_up(void)
{
	QWriteLocker writeLock(&g_lamexp_tools_lock);
	qWarning("------------ lamexp_tools_clean_up ------------");

	if(!g_lamexp_tools_data.isNull())
	{
		const QStringList keys = g_lamexp_tools_data->keys();
		for(QStringList::ConstIterator iter = keys.constBegin(); iter != keys.constEnd(); iter++)
		{
			tool_data_t currentTool = (*g_lamexp_tools_data)[*iter];
			MUTILS_DELETE(currentTool.first);
		}
		g_lamexp_tools_data->clear();
	}
}
Exemple #14
0
void Document::pages( QVector<Okular::Page*> * pagesVector )
{
    qSort( mEntries.begin(), mEntries.end(), caseSensitiveNaturalOrderLessThen );
    QScopedPointer< QIODevice > dev;

    int count = 0;
    pagesVector->clear();
    pagesVector->resize( mEntries.size() );
    QImageReader reader;
    foreach(const QString &file, mEntries) {
        if ( mArchive ) {
            const KArchiveFile *entry = static_cast<const KArchiveFile*>( mArchiveDir->entry( file ) );
            if ( entry ) {
                dev.reset( entry->createDevice() );
            }
        } else if ( mDirectory ) {
            dev.reset( mDirectory->createDevice( file ) );
        } else {
            dev.reset( mUnrar->createDevice( file ) );
        }

        if ( ! dev.isNull() ) {
            reader.setDevice( dev.data() );
            if ( reader.canRead() )
            {
                QSize pageSize = reader.size();
                if ( !pageSize.isValid() ) {
                    const QImage i = reader.read();
                    if ( !i.isNull() )
                        pageSize = i.size();
                }
                if ( pageSize.isValid() ) {
                    pagesVector->replace( count, new Okular::Page( count, pageSize.width(), pageSize.height(), Okular::Rotation0 ) );
                    mPageMap.append(file);
                    count++;
                } else {
                    qCDebug(OkularComicbookDebug) << "Ignoring" << file << "doesn't seem to be an image even if QImageReader::canRead returned true";
                }
            }
        }
    }
    pagesVector->resize( count );
}
Exemple #15
0
QAbstractButton *ResolveLocationContext::execLocationMessageBox(QWidget *parent,
                                                            const QString &file,
                                                            bool wantSkipButton)
{
    if (messageBox.isNull()) {
        messageBox.reset(new QMessageBox(QMessageBox::Warning,
                                         QrcEditor::tr("Invalid file location"),
                                         QString(), QMessageBox::NoButton, parent));
        copyButton = messageBox->addButton(QrcEditor::tr("Copy"), QMessageBox::ActionRole);
        abortButton = messageBox->addButton(QrcEditor::tr("Abort"), QMessageBox::RejectRole);
        messageBox->setDefaultButton(copyButton);
    }
    if (wantSkipButton && !skipButton) {
        skipButton = messageBox->addButton(QrcEditor::tr("Skip"), QMessageBox::DestructiveRole);
        messageBox->setEscapeButton(skipButton);
    }
    messageBox->setText(QrcEditor::tr("The file %1 is not in a subdirectory of the resource file. You now have the option to copy this file to a valid location.")
                    .arg(QDir::toNativeSeparators(file)));
    messageBox->exec();
    return messageBox->clickedButton();
}
Exemple #16
0
// Try to find a matching repository for a project by asking the VcsManager.
QString GerritPlugin::findLocalRepository(QString project, const QString &branch) const
{
    const QStringList gitRepositories = VcsManager::repositories(GitPlugin::instance()->gitVersionControl());
    // Determine key (file name) to look for (qt/qtbase->'qtbase').
    const int slashPos = project.lastIndexOf('/');
    if (slashPos != -1)
        project.remove(0, slashPos + 1);
    // When looking at branch 1.7, try to check folders
    // "qtbase_17", 'qtbase1.7' with a semi-smart regular expression.
    QScopedPointer<QRegExp> branchRegexp;
    if (!branch.isEmpty() && branch != "master") {
        QString branchPattern = branch;
        branchPattern.replace('.', "[\\.-_]?");
        const QString pattern = '^' + project
                                + "[-_]?"
                                + branchPattern + '$';
        branchRegexp.reset(new QRegExp(pattern));
        if (!branchRegexp->isValid())
            branchRegexp.reset(); // Oops.
    }
    for (const QString &repository : gitRepositories) {
        const QString fileName = Utils::FileName::fromString(repository).fileName();
        if ((!branchRegexp.isNull() && branchRegexp->exactMatch(fileName))
            || fileName == project) {
            // Perform a check on the branch.
            if (branch.isEmpty())  {
                return repository;
            } else {
                const QString repositoryBranch = GerritPlugin::branch(repository);
                if (repositoryBranch.isEmpty() || repositoryBranch == branch)
                    return repository;
            } // !branch.isEmpty()
        } // branchRegexp or file name match
    } // for repositories
    // No match, do we have  a projects folder?
    if (DocumentManager::useProjectsDirectory())
        return DocumentManager::projectsDirectory().toString();

    return QDir::currentPath();
}
Exemple #17
0
bool MUtils::Translation::insert(const QString &langId, const QString &qmFile, const QString &langName, const quint32 &systemId, const quint32 &country)
{
	QWriteLocker writeLockTranslations(&g_translation_lock);

	const QString key = langId.simplified().toLower();
	if(key.isEmpty() || qmFile.isEmpty() || langName.isEmpty() || (systemId < 1))
	{
		return false;
	}

	if(g_translation_data.isNull())
	{
		g_translation_data.reset(new translation_store_t());
	}

	if(g_translation_data->contains(key))
	{
		qWarning("Translation store already contains entry for '%s', going to replace!", MUTILS_UTF8(key));
	}

	g_translation_data->insert(key, MAKE_ENTRY(langName, qmFile, systemId, country));
	return true;
}
Exemple #18
0
QString ResolveLocationContext::execCopyFileDialog(QWidget *parent, const QDir &dir, const QString &targetPath)
{
    // Delayed creation of file dialog.
    if (copyFileDialog.isNull()) {
        copyFileDialog.reset(new QFileDialog(parent, QrcEditor::tr("Choose Copy Location")));
        copyFileDialog->setFileMode(QFileDialog::AnyFile);
        copyFileDialog->setAcceptMode(QFileDialog::AcceptSave);
    }
    copyFileDialog->selectFile(targetPath);
    // Repeat until the path entered is no longer above 'dir'
    // (relative is not "../").
    while (true) {
        if (copyFileDialog->exec() != QDialog::Accepted)
            return QString();
        const QStringList files = copyFileDialog->selectedFiles();
        if (files.isEmpty())
            return QString();
        const QString relPath = dir.relativeFilePath(files.front());
        if (!relPath.startsWith(QLatin1String("../")))
            return files.front();
    }
    return QString();
}
Exemple #19
0
/*
 * Register tool
 */
void lamexp_tools_register(const QString &toolName, LockedFile *const file, const quint32 &version, const QString &tag)
{
	QWriteLocker writeLock(&g_lamexp_tools_lock);
	
	if(!file)
	{
		MUTILS_THROW("lamexp_register_tool: Tool file must not be NULL!");
	}

	if(g_lamexp_tools_data.isNull())
	{
		g_lamexp_tools_data.reset(new tool_hash_t());
		atexit(lamexp_tools_clean_up);
	}

	const QString key = toolName.simplified().toLower();
	if(g_lamexp_tools_data->contains(key))
	{
		MUTILS_THROW("lamexp_register_tool: Tool is already registered!");
	}

	g_lamexp_tools_data->insert(key, MAKE_ENTRY(file, version, tag));
}
Exemple #20
0
/*
 * Lookup tool version
 */
const quint32 &lamexp_tools_version(const QString &toolName, QString *const tagOut)
{
	QReadLocker readLock(&g_lamexp_tools_lock);

	if(!g_lamexp_tools_data.isNull())
	{
		const QString key = toolName.simplified().toLower();
		if(g_lamexp_tools_data->contains(key))
		{
			const tool_info_t &info = (*g_lamexp_tools_data)[key].second;
			if(tagOut)
			{
				*tagOut = info.second;
			}
			return info.first;
		}
	}

	if(tagOut)
	{
		tagOut->clear();
	}
	return g_max_uint32;
}
QList<double> QgsGraduatedSymbolRendererV2::getDataValues( QgsVectorLayer *vlayer )
{
  QList<double> values;
  QScopedPointer<QgsExpression> expression;
  int attrNum = vlayer->fieldNameIndex( mAttrName );

  if ( attrNum == -1 )
  {
    // try to use expression
    expression.reset( new QgsExpression( mAttrName ) );
    if ( expression->hasParserError() || !expression->prepare( vlayer->pendingFields() ) )
      return values; // should have a means to report errors
  }

  QgsFeature f;
  QStringList lst;
  if ( expression.isNull() )
    lst.append( mAttrName );
  else
    lst = expression->referencedColumns();

  QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest()
                           .setFlags(( expression && expression->needsGeometry() ) ?
                                     QgsFeatureRequest::NoFlags :
                                     QgsFeatureRequest::NoGeometry )
                           .setSubsetOfAttributes( lst, vlayer->pendingFields() ) );

  // create list of non-null attribute values
  while ( fit.nextFeature( f ) )
  {
    QVariant v = expression ? expression->evaluate( f ) : f.attribute( attrNum );
    if ( !v.isNull() )
      values.append( v.toDouble() );
  }
  return values;
}
Exemple #22
0
void tst_qqmlexpression::expressionFromDataComponent()
{
    qmlRegisterType<TestObject>("Test", 1, 0, "TestObject");

    QQmlEngine engine;
    QQmlComponent c(&engine);

    QUrl url = testFileUrl("expressionFromDataComponent.qml");

    {
        QFile f(url.toLocalFile());
        QVERIFY(f.open(QIODevice::ReadOnly));
        c.setData(f.readAll(), url);
    }

    QScopedPointer<TestObject> object;
    object.reset(qobject_cast<TestObject*>(c.create()));
    Q_ASSERT(!object.isNull());

    QQmlExpression expression(object->scriptString());
    QVariant result = expression.evaluate();
    QVERIFY(result.type() == QVariant::String);
    QCOMPARE(result.toString(), QStringLiteral("success"));
}
Exemple #23
0
bool MUtils::Translation::install_translator_from_file(const QString &qmFile)
{
	QWriteLocker writeLock(&g_translation_lock);

	if(g_translation_inst.isNull())
	{
		g_translation_inst.reset(new QTranslator());
	}

	if(qmFile.isEmpty())
	{
		QApplication::removeTranslator(g_translation_inst.data());
		return true;
	}

	const QFileInfo qmFileInfo(qmFile);
	if(!(qmFileInfo.exists() && qmFileInfo.isFile()))
	{
		qWarning("Translation file not found:\n\"%s\"", MUTILS_UTF8(qmFile));
		return false;
	}

	const QString qmPath = QFileInfo(qmFile).canonicalFilePath();
	if(!qmPath.isEmpty())
	{
		QApplication::removeTranslator(g_translation_inst.data());
		if(g_translation_inst->load(qmPath))
		{
			QApplication::installTranslator(g_translation_inst.data());
			return true;
		}
	}

	qWarning("Failed to load translation:\n\"%s\"",  MUTILS_UTF8(qmFile));
	return false;
}
QgsGraduatedSymbolRendererV2* QgsGraduatedSymbolRendererV2::createRenderer(
  QgsVectorLayer* vlayer,
  QString attrName,
  int classes,
  Mode mode,
  QgsSymbolV2* symbol,
  QgsVectorColorRampV2* ramp,
  bool inverted )
{
  if ( classes < 1 )
    return NULL;

  int attrNum = vlayer->fieldNameIndex( attrName );
  double minimum;
  double maximum;

  QScopedPointer<QgsExpression> expression;

  if ( attrNum == -1 )
  {
    // try to use expression
    expression.reset( new QgsExpression( attrName ) );
    if ( expression->hasParserError() || !expression->prepare( vlayer->pendingFields() ) )
      return 0; // should have a means to report errors

    QList<double> values;
    QgsFeatureIterator fit = vlayer->getFeatures();
    QgsFeature feature;
    while ( fit.nextFeature( feature ) )
    {
      values << expression->evaluate( feature ).toDouble();
    }
    qSort( values );
    minimum = values.first();
    maximum = values.last();
  }
  else
  {
    minimum = vlayer->minimumValue( attrNum ).toDouble();
    maximum = vlayer->maximumValue( attrNum ).toDouble();
  }

  QgsDebugMsg( QString( "min %1 // max %2" ).arg( minimum ).arg( maximum ) );
  QList<double> breaks;
  QList<int> labels;
  if ( mode == EqualInterval )
  {
    breaks = _calcEqualIntervalBreaks( minimum, maximum, classes );
  }
  else if ( mode == Pretty )
  {
    breaks = _calcPrettyBreaks( minimum, maximum, classes );
  }
  else if ( mode == Quantile || mode == Jenks || mode == StdDev )
  {
    // get values from layer
    QList<double> values;
    QgsFeature f;
    QStringList lst;
    if ( expression.isNull() )
      lst.append( attrName );
    else
      lst = expression->referencedColumns();

    QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFlags( QgsFeatureRequest::NoGeometry ).setSubsetOfAttributes( lst, vlayer->pendingFields() ) );

    // create list of non-null attribute values
    while ( fit.nextFeature( f ) )
    {
      QVariant v = expression.isNull() ? f.attribute( attrNum ) : expression->evaluate( f );
      if ( !v.isNull() )
        values.append( v.toDouble() );
    }

    // calculate the breaks
    if ( mode == Quantile )
    {
      breaks = _calcQuantileBreaks( values, classes );
    }
    else if ( mode == Jenks )
    {
      breaks = _calcJenksBreaks( values, classes, minimum, maximum );
    }
    else if ( mode == StdDev )
    {
      breaks = _calcStdDevBreaks( values, classes, labels );
    }
  }
  else
  {
    Q_ASSERT( false );
  }

  QgsRangeList ranges;
  double lower, upper = minimum;
  QString label;

  // "breaks" list contains all values at class breaks plus maximum as last break
  int i = 0;
  for ( QList<double>::iterator it = breaks.begin(); it != breaks.end(); ++it, ++i )
  {
    lower = upper; // upper border from last interval
    upper = *it;
    if ( mode == StdDev )
    {
      if ( i == 0 )
      {
        label = "< " + QString::number( labels[i], 'i', 0 ) + " Std Dev";
      }
      else if ( i == labels.count() - 1 )
      {
        label = ">= " + QString::number( labels[i-1], 'i', 0 ) + " Std Dev";
      }
      else
      {
        label = QString::number( labels[i-1], 'i', 0 ) + " Std Dev" + " - " + QString::number( labels[i], 'i', 0 ) + " Std Dev";
      }
    }
    else
    {
      label = QString::number( lower, 'f', 4 ) + " - " + QString::number( upper, 'f', 4 );
    }

    QgsSymbolV2* newSymbol = symbol->clone();
    double colorValue;
    if ( inverted ) colorValue = ( breaks.count() > 1 ? ( double )( breaks.count() - i - 1 ) / ( breaks.count() - 1 ) : 0 );
    else colorValue = ( breaks.count() > 1 ? ( double ) i / ( breaks.count() - 1 ) : 0 );
    newSymbol->setColor( ramp->color( colorValue ) ); // color from (0 / cl-1) to (cl-1 / cl-1)

    ranges.append( QgsRendererRangeV2( lower, upper, newSymbol, label ) );
  }

  QgsGraduatedSymbolRendererV2* r = new QgsGraduatedSymbolRendererV2( attrName, ranges );
  r->setSourceSymbol( symbol->clone() );
  r->setSourceColorRamp( ramp->clone() );
  r->setInvertedColorRamp( inverted );
  r->setMode( mode );
  return r;
}
int QgsAtlasComposition::updateFeatures()
{
  //needs to be called when layer, filter, sort changes

  if ( !mCoverageLayer )
  {
    return 0;
  }

  QgsExpressionContext expressionContext = createExpressionContext();

  updateFilenameExpression();

  // select all features with all attributes
  QgsFeatureRequest req;

  QScopedPointer<QgsExpression> filterExpression;
  if ( mFilterFeatures && !mFeatureFilter.isEmpty() )
  {
    filterExpression.reset( new QgsExpression( mFeatureFilter ) );
    if ( filterExpression->hasParserError() )
    {
      mFilterParserError = filterExpression->parserErrorString();
      return 0;
    }

    //filter good to go
    req.setFilterExpression( mFeatureFilter );
  }
  mFilterParserError = QString();

  QgsFeatureIterator fit = mCoverageLayer->getFeatures( req );

  QScopedPointer<QgsExpression> nameExpression;
  if ( !mPageNameExpression.isEmpty() )
  {
    nameExpression.reset( new QgsExpression( mPageNameExpression ) );
    if ( nameExpression->hasParserError() )
    {
      nameExpression.reset( nullptr );
    }
    else
    {
      nameExpression->prepare( &expressionContext );
    }
  }

  // We cannot use nextFeature() directly since the feature pointer is rewinded by the rendering process
  // We thus store the feature ids for future extraction
  QgsFeature feat;
  mFeatureIds.clear();
  mFeatureKeys.clear();
  int sortIdx = mCoverageLayer->fields().lookupField( mSortKeyAttributeName );

  while ( fit.nextFeature( feat ) )
  {
    expressionContext.setFeature( feat );

    QString pageName;
    if ( !nameExpression.isNull() )
    {
      QVariant result = nameExpression->evaluate( &expressionContext );
      if ( nameExpression->hasEvalError() )
      {
        QgsMessageLog::logMessage( tr( "Atlas name eval error: %1" ).arg( nameExpression->evalErrorString() ), tr( "Composer" ) );
      }
      pageName = result.toString();
    }

    mFeatureIds.push_back( qMakePair( feat.id(), pageName ) );

    if ( mSortFeatures && sortIdx != -1 )
    {
      mFeatureKeys.insert( feat.id(), feat.attributes().at( sortIdx ) );
    }
  }

  // sort features, if asked for
  if ( !mFeatureKeys.isEmpty() )
  {
    FieldSorter sorter( mFeatureKeys, mSortAscending );
    qSort( mFeatureIds.begin(), mFeatureIds.end(), sorter );
  }

  emit numberFeaturesChanged( mFeatureIds.size() );

  //jump to first feature if currently using an atlas preview
  //need to do this in case filtering/layer change has altered matching features
  if ( mComposition->atlasMode() == QgsComposition::PreviewAtlas )
  {
    firstFeature();
  }

  return mFeatureIds.size();
}
QVariant QgsAggregateCalculator::calculate( QgsAggregateCalculator::Aggregate aggregate,
    const QString& fieldOrExpression,
    QgsExpressionContext* context, bool* ok ) const
{
  if ( ok )
    *ok = false;

  if ( !mLayer )
    return QVariant();

  QScopedPointer<QgsExpression> expression;
  QScopedPointer<QgsExpressionContext> defaultContext;
  if ( !context )
  {
    defaultContext.reset( createContext() );
    context = defaultContext.data();
  }

  int attrNum = mLayer->fieldNameIndex( fieldOrExpression );

  if ( attrNum == -1 )
  {
    Q_ASSERT( context );
    context->setFields( mLayer->fields() );
    // try to use expression
    expression.reset( new QgsExpression( fieldOrExpression ) );

    if ( expression->hasParserError() || !expression->prepare( context ) )
    {
      return QVariant();
    }
  }

  QStringList lst;
  if ( expression.isNull() )
    lst.append( fieldOrExpression );
  else
    lst = expression->referencedColumns();

  QgsFeatureRequest request = QgsFeatureRequest()
                              .setFlags(( expression.data() && expression->needsGeometry() ) ?
                                        QgsFeatureRequest::NoFlags :
                                        QgsFeatureRequest::NoGeometry )
                              .setSubsetOfAttributes( lst, mLayer->fields() );
  if ( !mFilterExpression.isEmpty() )
    request.setFilterExpression( mFilterExpression );
  if ( context )
    request.setExpressionContext( *context );

  //determine result type
  QVariant::Type resultType = QVariant::Double;
  if ( attrNum == -1 )
  {
    // evaluate first feature, check result type
    QgsFeatureRequest testRequest( request );
    testRequest.setLimit( 1 );
    QgsFeature f;
    QgsFeatureIterator fit = mLayer->getFeatures( testRequest );
    if ( !fit.nextFeature( f ) )
    {
      //no matching features
      if ( ok )
        *ok = true;
      return QVariant();
    }

    if ( context )
      context->setFeature( f );
    QVariant v = expression->evaluate( context );
    resultType = v.type();
  }
  else
  {
    resultType = mLayer->fields().at( attrNum ).type();
  }

  QgsFeatureIterator fit = mLayer->getFeatures( request );
  return calculate( aggregate, fit, resultType, attrNum, expression.data(), mDelimiter, context, ok );
}
bool QgsComposerAttributeTableV2::getTableContents( QgsComposerTableContents &contents )
{
  contents.clear();

  if (( mSource == QgsComposerAttributeTableV2::AtlasFeature || mSource == QgsComposerAttributeTableV2::RelationChildren )
      && !mComposition->atlasComposition().enabled() )
  {
    //source mode requires atlas, but atlas disabled
    return false;
  }

  QgsVectorLayer* layer = sourceLayer();

  if ( !layer )
  {
    //no source layer
    return false;
  }

  //prepare filter expression
  QScopedPointer<QgsExpression> filterExpression;
  bool activeFilter = false;
  if ( mFilterFeatures && !mFeatureFilter.isEmpty() )
  {
    filterExpression.reset( new QgsExpression( mFeatureFilter ) );
    if ( !filterExpression->hasParserError() )
    {
      activeFilter = true;
    }
  }

  QgsRectangle selectionRect;
  if ( mComposerMap && mShowOnlyVisibleFeatures )
  {
    selectionRect = *mComposerMap->currentMapExtent();
    if ( layer && mComposition->mapSettings().hasCrsTransformEnabled() )
    {
      //transform back to layer CRS
      QgsCoordinateTransform coordTransform( layer->crs(), mComposition->mapSettings().destinationCrs() );
      try
      {
        selectionRect = coordTransform.transformBoundingBox( selectionRect, QgsCoordinateTransform::ReverseTransform );
      }
      catch ( QgsCsException &cse )
      {
        Q_UNUSED( cse );
        return false;
      }
    }
  }

  QgsFeatureRequest req;

  if ( mSource == QgsComposerAttributeTableV2::RelationChildren )
  {
    QgsRelation relation = QgsProject::instance()->relationManager()->relation( mRelationId );
    QgsFeature* atlasFeature = mComposition->atlasComposition().currentFeature();
    if ( atlasFeature )
    {
      req = relation.getRelatedFeaturesRequest( *atlasFeature );
    }
    else
    {
      //no atlas feature, so empty table
      return true;
    }
  }

  if ( !selectionRect.isEmpty() )
    req.setFilterRect( selectionRect );

  req.setFlags( mShowOnlyVisibleFeatures ? QgsFeatureRequest::ExactIntersect : QgsFeatureRequest::NoFlags );

  if ( mSource == QgsComposerAttributeTableV2::AtlasFeature
       && mComposition->atlasComposition().enabled() )
  {
    //source mode is current atlas feature
    QgsFeature* atlasFeature = mComposition->atlasComposition().currentFeature();
    if ( atlasFeature )
    {
      req.setFilterFid( atlasFeature->id() );
    }
    else
    {
      //no atlas feature, so empty table
      return true;
    }
  }

  QgsFeature f;
  int counter = 0;
  QgsFeatureIterator fit = layer->getFeatures( req );

  while ( fit.nextFeature( f ) && counter < mMaximumNumberOfFeatures )
  {
    //check feature against filter
    if ( activeFilter && !filterExpression.isNull() )
    {
      QVariant result = filterExpression->evaluate( &f, layer->pendingFields() );
      // skip this feature if the filter evaluation is false
      if ( !result.toBool() )
      {
        continue;
      }
    }
    //check against atlas feature intersection
    if ( mFilterToAtlasIntersection )
    {
      if ( !f.geometry() || ! mComposition->atlasComposition().enabled() )
      {
        continue;
      }
      QgsFeature* atlasFeature = mComposition->atlasComposition().currentFeature();
      if ( !atlasFeature || !atlasFeature->geometry() ||
           !f.geometry()->intersects( atlasFeature->geometry() ) )
      {
        //feature falls outside current atlas feature
        continue;
      }
    }

    QgsComposerTableRow currentRow;

    QList<QgsComposerTableColumn*>::const_iterator columnIt = mColumns.constBegin();
    for ( ; columnIt != mColumns.constEnd(); ++columnIt )
    {
      int idx = layer->fieldNameIndex(( *columnIt )->attribute() );
      if ( idx != -1 )
      {
        currentRow << f.attributes()[idx];
      }
      else
      {
        // Lets assume it's an expression
        QgsExpression* expression = new QgsExpression(( *columnIt )->attribute() );
        expression->setCurrentRowNumber( counter + 1 );
        expression->prepare( layer->pendingFields() );
        QVariant value = expression->evaluate( f );
        currentRow << value;
      }
    }

    if ( !mShowUniqueRowsOnly || !contentsContainsRow( contents, currentRow ) )
    {
      contents << currentRow;
      ++counter;
    }
  }

  //sort the list, starting with the last attribute
  QgsComposerAttributeTableCompareV2 c;
  QList< QPair<int, bool> > sortColumns = sortAttributes();
  for ( int i = sortColumns.size() - 1; i >= 0; --i )
  {
    c.setSortColumn( sortColumns.at( i ).first );
    c.setAscending( sortColumns.at( i ).second );
    qStableSort( contents.begin(), contents.end(), c );
  }

  recalculateTableSize();
  return true;
}
bool ScSlaInfoReader::readInfos(const QString& fileName)
{
	bool isScribusDocument = false;
	bool readInfoSuccess   = false;
	bool firstStartElement = true;
	QScopedPointer<QIODevice> file;

	resetFileInfos();
	QFile aFile;
	if (fileName.right(2).toLower() == "gz")
	{
		aFile.setFileName(fileName);
		QtIOCompressor *compressor = new QtIOCompressor(&aFile);
		compressor->setStreamFormat(QtIOCompressor::GzipFormat);
		file.reset(compressor);
	}
	else
		file.reset( new QFile(fileName) );

	if (file.isNull() || !file->open(QIODevice::ReadOnly))
		return false;

	QByteArray bytes = file->read(512);
	if (!bytes.contains("SCRIBUS") && !bytes.contains("SCRIBUSUTF8") && !bytes.contains("SCRIBUSUTF8NEW"))
	{
		file->close();
		return false;
	}
	file->reset();

	QXmlStreamReader reader(file.data());
	while (!reader.atEnd() && !reader.hasError())
	{
		QXmlStreamReader::TokenType ttype = reader.readNext();
		if (reader.hasError()) break;

		if (ttype == QXmlStreamReader::StartElement)
		{
			QStringRef nodeName = reader.name();
			if (firstStartElement)
			{
				if (nodeName == "SCRIBUS" || nodeName == "SCRIBUSUTF8" || nodeName == "SCRIBUSUTF8NEW")
				{
					QXmlStreamAttributes attrs = reader.attributes();
					m_format = attrs.value(QLatin1String("Version")).toString();
					isScribusDocument = true;
				}
				else
				{
					isScribusDocument = false;
					break;
				}
			}
			else if (nodeName == "DOCUMENT")
			{
				QXmlStreamAttributes attrs = reader.attributes();
				m_title  = attrs.value(QLatin1String("TITLE")).toString();
				m_author = attrs.value(QLatin1String("AUTHOR")).toString();
				readInfoSuccess = true;
				break;
			}
			firstStartElement = false;
		}
	}
	isScribusDocument &= !reader.hasError();
	file->close();

	return (isScribusDocument && readInfoSuccess);
}
void StateListener::slotStateChanged()
{
    // Get the current file. Are we on a temporary submit editor indicated by
    // temporary path prefix or does the file contains a hash, indicating a project
    // folder?
    State state;
    IDocument *currentDocument = EditorManager::currentDocument();
    if (!currentDocument) {
        state.currentFile.clear();
    } else {
        state.currentFile = currentDocument->filePath().toString();
        if (state.currentFile.isEmpty() || currentDocument->isTemporary())
            state.currentFile = VcsBasePlugin::source(currentDocument);
    }
    QScopedPointer<QFileInfo> currentFileInfo; // Instantiate QFileInfo only once if required.
    if (!state.currentFile.isEmpty()) {
        const bool isTempFile = state.currentFile.startsWith(QDir::tempPath());
        // Quick check: Does it look like a patch?
        const bool isPatch = state.currentFile.endsWith(QLatin1String(".patch"))
                             || state.currentFile.endsWith(QLatin1String(".diff"));
        if (isPatch) {
            // Patch: Figure out a name to display. If it is a temp file, it could be
            // Codepaster. Use the display name of the editor.
            state.currentPatchFile = state.currentFile;
            if (isTempFile)
                state.currentPatchFileDisplayName = displayNameOfEditor(state.currentPatchFile);
            if (state.currentPatchFileDisplayName.isEmpty()) {
                currentFileInfo.reset(new QFileInfo(state.currentFile));
                state.currentPatchFileDisplayName = currentFileInfo->fileName();
            }
        }
        // For actual version control operations on it:
        // Do not show temporary files and project folders ('#')
        if (isTempFile || state.currentFile.contains(QLatin1Char('#')))
            state.currentFile.clear();
    }

    // Get the file and its control. Do not use the file unless we find one
    IVersionControl *fileControl = 0;
    if (!state.currentFile.isEmpty()) {
        if (currentFileInfo.isNull())
            currentFileInfo.reset(new QFileInfo(state.currentFile));
        if (currentFileInfo->isDir()) {
            state.currentFile.clear();
            state.currentFileDirectory = currentFileInfo->absoluteFilePath();
        } else {
            state.currentFileDirectory = currentFileInfo->absolutePath();
            state.currentFileName = currentFileInfo->fileName();
        }
        fileControl = VcsManager::findVersionControlForDirectory(
                    state.currentFileDirectory,
                    &state.currentFileTopLevel);
        if (!fileControl)
            state.clearFile();
    }
    // Check for project, find the control
    IVersionControl *projectControl = 0;
    Project *currentProject = ProjectTree::currentProject();
    if (!currentProject)
        currentProject = SessionManager::startupProject();
    if (currentProject) {
        state.currentProjectPath = currentProject->projectDirectory().toString();
        state.currentProjectName = currentProject->displayName();
        projectControl = VcsManager::findVersionControlForDirectory(state.currentProjectPath,
                                                                    &state.currentProjectTopLevel);
        if (projectControl) {
            // If we have both, let the file's one take preference
            if (fileControl && projectControl != fileControl)
                state.clearProject();
        } else {
            state.clearProject(); // No control found
        }
    }
    // Assemble state and emit signal.
    IVersionControl *vc = fileControl;
    if (!vc)
        vc = projectControl;
    if (!vc)
        state.clearPatchFile(); // Need a repository to patch
    if (debug)
        qDebug() << state << (vc ? vc->displayName() : QLatin1String("No version control"));
    EditorManager::updateWindowTitles();
    emit stateChanged(state, vc);
}
bool QgsComposerAttributeTable::getFeatureAttributes( QList<QgsAttributeMap> &attributeMaps )
{
  if ( !mVectorLayer )
  {
    return false;
  }

  QScopedPointer< QgsExpressionContext > context( createExpressionContext() );
  context->setFields( mVectorLayer->fields() );

  attributeMaps.clear();

  //prepare filter expression
  QScopedPointer<QgsExpression> filterExpression;
  bool activeFilter = false;
  if ( mFilterFeatures && !mFeatureFilter.isEmpty() )
  {
    filterExpression.reset( new QgsExpression( mFeatureFilter ) );
    if ( !filterExpression->hasParserError() )
    {
      activeFilter = true;
    }
  }

  QgsRectangle selectionRect;
  if ( mComposerMap && mShowOnlyVisibleFeatures )
  {
    selectionRect = *mComposerMap->currentMapExtent();
    if ( mComposition->mapSettings().hasCrsTransformEnabled() )
    {
      //transform back to layer CRS
      QgsCoordinateTransform coordTransform( mVectorLayer->crs(), mComposition->mapSettings().destinationCrs() );
      try
      {
        selectionRect = coordTransform.transformBoundingBox( selectionRect, QgsCoordinateTransform::ReverseTransform );
      }
      catch ( QgsCsException &cse )
      {
        Q_UNUSED( cse );
        return false;
      }
    }
  }

  QgsFeatureRequest req;
  if ( !selectionRect.isEmpty() )
    req.setFilterRect( selectionRect );

  req.setFlags( mShowOnlyVisibleFeatures ? QgsFeatureRequest::ExactIntersect : QgsFeatureRequest::NoFlags );

  QgsFeature f;
  int counter = 0;
  QgsFeatureIterator fit = mVectorLayer->getFeatures( req );

  while ( fit.nextFeature( f ) && counter < mMaximumNumberOfFeatures )
  {
    context->setFeature( f );
    //check feature against filter
    if ( activeFilter && !filterExpression.isNull() )
    {
      QVariant result = filterExpression->evaluate( context.data() );
      // skip this feature if the filter evaluation is false
      if ( !result.toBool() )
      {
        continue;
      }
    }

    attributeMaps.push_back( QgsAttributeMap() );

    QList<QgsComposerTableColumn*>::const_iterator columnIt = mColumns.constBegin();
    int i = 0;
    for ( ; columnIt != mColumns.constEnd(); ++columnIt )
    {
      int idx = mVectorLayer->fieldNameIndex(( *columnIt )->attribute() );
      if ( idx != -1 )
      {
        attributeMaps.last().insert( i, f.attributes().at( idx ) );
      }
      else
      {
        // Lets assume it's an expression
        QgsExpression* expression = new QgsExpression(( *columnIt )->attribute() );
        context->lastScope()->setVariable( QString( "row_number" ), counter + 1 );
        expression->prepare( context.data() );
        QVariant value = expression->evaluate( context.data() );
        attributeMaps.last().insert( i, value.toString() );
      }

      i++;
    }
    ++counter;
  }

  //sort the list, starting with the last attribute
  QgsComposerAttributeTableCompare c;
  QList< QPair<int, bool> > sortColumns = sortAttributes();
  for ( int i = sortColumns.size() - 1; i >= 0; --i )
  {
    c.setSortColumn( sortColumns.at( i ).first );
    c.setAscending( sortColumns.at( i ).second );
    qStableSort( attributeMaps.begin(), attributeMaps.end(), c );
  }

  adjustFrameToSize();
  return true;
}