Example #1
0
// TODO: remove me, this is taken from cppeditor.cpp. Find some common place for this method
static Document::Ptr findDefinition(const Function *functionDeclaration, int *line)
{
    CppTools::CppModelManagerInterface *cppModelManager = cppModelManagerInstance();
    if (!cppModelManager)
        return Document::Ptr();

    QVector<const Name *> qualifiedName;
    Scope *scope = functionDeclaration->scope();
    for (; scope; scope = scope->enclosingScope()) {
        if (scope->isClassScope() || scope->isNamespaceScope()) {
            if (scope->owner() && scope->owner()->name()) {
                const Name *scopeOwnerName = scope->owner()->name();
                if (const QualifiedNameId *q = scopeOwnerName->asQualifiedNameId()) {
                    for (unsigned i = 0; i < q->nameCount(); ++i) {
                        qualifiedName.prepend(q->nameAt(i));

                    }
                } else {
                    qualifiedName.prepend(scopeOwnerName);
                }
            }
        }
    }

    qualifiedName.append(functionDeclaration->name());

    Control control;
    const QualifiedNameId *q = control.qualifiedNameId(&qualifiedName[0], qualifiedName.size());
    LookupContext context(&control);
    const Snapshot documents = cppModelManager->snapshot();
    foreach (Document::Ptr doc, documents) {
        QList<Scope *> visibleScopes;
        visibleScopes.append(doc->globalSymbols());
        visibleScopes = context.expand(visibleScopes);
        foreach (Scope *visibleScope, visibleScopes) {
            Symbol *symbol = 0;
            if (const NameId *nameId = q->unqualifiedNameId()->asNameId())
                symbol = visibleScope->lookat(nameId->identifier());
            else if (const DestructorNameId *dtorId = q->unqualifiedNameId()->asDestructorNameId())
                symbol = visibleScope->lookat(dtorId->identifier());
            else if (const TemplateNameId *templNameId = q->unqualifiedNameId()->asTemplateNameId())
                symbol = visibleScope->lookat(templNameId->identifier());
            else if (const OperatorNameId *opId = q->unqualifiedNameId()->asOperatorNameId())
                symbol = visibleScope->lookat(opId->kind());
            // ### cast operators
            for (; symbol; symbol = symbol->next()) {
                if (! symbol->isFunction())
                    continue;
                else if (! isCompatible(symbol->asFunction(), functionDeclaration, q))
                    continue;
                *line = symbol->line(); // TODO: shift the line so that we are inside a function. Maybe just find the nearest '{'?
                return doc;
            }
        }
void MainWindow::reduire_mesure(QVector<double> & _data)
{
    double valeur;
    for(int i=0;i<TAILLE_BUFFER_VISUALISATION;i++)
    {
        double min = _data.at(i*TAILLE_BUFFER_ACQUISITION/TAILLE_BUFFER_VISUALISATION);
        double max = _data.at(i*TAILLE_BUFFER_ACQUISITION/TAILLE_BUFFER_VISUALISATION);
        valeur=0;
        for(int j=0;j<TAILLE_BUFFER_ACQUISITION/TAILLE_BUFFER_VISUALISATION;j++)
        {
            /*if(_data.at(i*(TAILLE_BUFFER_ACQUISITION/TAILLE_BUFFER_VISUALISATION)+j)<min)
            {
                min = _data.at(i*(TAILLE_BUFFER_ACQUISITION/TAILLE_BUFFER_VISUALISATION)+j);
            }
            if(_data.at(i*(TAILLE_BUFFER_ACQUISITION/TAILLE_BUFFER_VISUALISATION)+j)>max)
            {
                max = _data.at(i*(TAILLE_BUFFER_ACQUISITION/TAILLE_BUFFER_VISUALISATION)+j);
            }*/
            valeur+=_data.at(i*(TAILLE_BUFFER_ACQUISITION/TAILLE_BUFFER_VISUALISATION)+j);
        }
        //valeur-=(min+max);
        _data.prepend(valeur/(double)((TAILLE_BUFFER_ACQUISITION/TAILLE_BUFFER_VISUALISATION)/*-2*/));
    }
    _data.resize(TAILLE_BUFFER_VISUALISATION);
}
void MainWindow::decaler_mesure(QVector<double> & _data, int decalage)
{
    for(int i=TAILLE_BUFFER_ACQUISITION-1;i>decalage;i--)
    {
        _data.prepend(_data.at(i));
    }
    _data.resize(TAILLE_BUFFER_ACQUISITION);
}
Example #4
0
HelpViewer *HelpPlugin::createHelpViewer(qreal zoom)
{
    // check for backends
    typedef std::function<HelpViewer *()> ViewerFactory;
    typedef QPair<QByteArray, ViewerFactory>  ViewerFactoryItem; // id -> factory
    QVector<ViewerFactoryItem> factories;
#ifndef QT_NO_WEBKIT
    factories.append(qMakePair(QByteArray("qtwebkit"), []() { return new QtWebKitHelpViewer(); }));
#endif
#ifdef QTC_WEBENGINE_HELPVIEWER
    factories.append(qMakePair(QByteArray("qtwebengine"), []() { return new WebEngineHelpViewer(); }));
#endif
    factories.append(qMakePair(QByteArray("textbrowser"), []() { return new TextBrowserHelpViewer(); }));

#ifdef QTC_MAC_NATIVE_HELPVIEWER
    // default setting
#ifdef QTC_MAC_NATIVE_HELPVIEWER_DEFAULT
     factories.prepend(qMakePair(QByteArray("native"), []() { return new MacWebKitHelpViewer(); }));
#else
     factories.append(qMakePair(QByteArray("native"), []() { return new MacWebKitHelpViewer(); }));
#endif
#endif

    HelpViewer *viewer = nullptr;

    // check requested backend
    const QByteArray backend = qgetenv("QTC_HELPVIEWER_BACKEND");
    if (!backend.isEmpty()) {
        const int pos = Utils::indexOf(factories, [backend](const ViewerFactoryItem &item) {
            return backend == item.first;
        });
        if (pos == -1) {
            qWarning("Help viewer backend \"%s\" not found, using default.", backend.constData());
        } else {
            viewer  = factories.at(pos).second();
        }
    }

    if (!viewer)
        viewer = factories.first().second();
    QTC_ASSERT(viewer, return nullptr);

    // initialize font
    viewer->setViewerFont(LocalHelpManager::fallbackFont());
    connect(LocalHelpManager::instance(), &LocalHelpManager::fallbackFontChanged,
            viewer, &HelpViewer::setViewerFont);

    // initialize zoom
    viewer->setScale(zoom);

    // add find support
    Aggregation::Aggregate *agg = new Aggregation::Aggregate();
    agg->add(viewer);
    agg->add(new HelpViewerFindSupport(viewer));

    return viewer;
}
Example #5
0
void CompletionModel::updateCompletion(const QString &text, FindFlags f)
{
    if (text.isEmpty())
         return;
     beginResetModel();
     Utils::erase(m_entries, Utils::equal(&CompletionEntry::text, text));
     m_entries.prepend({text, f});
     while (m_entries.size() > MAX_COMPLETIONS)
         m_entries.removeLast();
     endResetModel();
}
Example #6
0
    /**
     * Create new spline and precalculate some values
     * for future
     *
     * @a - base points of the spline
     */
    void createSpline(const QList<T_point> &a) {
        int intervals = m_intervals = a.size() - 1;
        int i;
        m_begin = a.first().x();
        m_end = a.last().x();

        m_a.clear();
        m_b.resize(intervals);
        m_c.clear();
        m_d.resize(intervals);
        m_h.resize(intervals);

        for (i = 0; i < intervals; i++) {
            m_h[i] = a[i+1].x() - a[i].x();
            m_a.append(a[i].y());
        }
        m_a.append(a.last().y());


        QList<T> tri_b;
        QList<T> tri_f;
        QList<T> tri_a; /* equals to @tri_c */

        for (i = 0; i < intervals - 1; i++) {
            tri_b.append(2.*(m_h[i] + m_h[i+1]));

            tri_f.append(6.*((m_a[i+2] - m_a[i+1]) / m_h[i+1] - (m_a[i+1] - m_a[i]) / m_h[i]));
        }
        for (i = 1; i < intervals - 1; i++)
            tri_a.append(m_h[i]);

        if (intervals > 1) {
            m_c = KisTridiagonalSystem<T>::calculate(tri_a, tri_b, tri_a, tri_f);
        }
        m_c.prepend(0);
        m_c.append(0);

        for (i = 0; i < intervals; i++)
            m_d[i] = (m_c[i+1] - m_c[i]) / m_h[i];

        for (i = 0; i < intervals; i++)
            m_b[i] = -0.5 * (m_c[i] * m_h[i])  - (1 / 6.0) * (m_d[i] * m_h[i] * m_h[i]) + (m_a[i+1] - m_a[i]) / m_h[i];
    }
Example #7
0
/*! \internal
    Adds an adopted thread to the list of threads that Qt watches to make sure
    the thread data is properly cleaned up. This function starts the watcher
    thread if necessary.
*/
void qt_watch_adopted_thread(const HANDLE adoptedThreadHandle, QThread *qthread)
{
    QMutexLocker lock(&qt_adopted_thread_watcher_mutex);
    qt_adopted_thread_handles.append(adoptedThreadHandle);
    qt_adopted_qthreads.append(qthread);

    // Start watcher thread if it is not already running.
    if (qt_adopted_thread_watcher_handle == 0) {
        if (qt_adopted_thread_wakeup == 0) {
            qt_adopted_thread_wakeup = QT_WA_INLINE(CreateEventW(0, false, false, 0),
                                                    CreateEventA(0, false, false, 0));
            qt_adopted_thread_handles.prepend(qt_adopted_thread_wakeup);
        }

        qt_adopted_thread_watcher_handle =
            (HANDLE)_beginthread(qt_adopted_thread_watcher_function, 0, NULL);
    } else {
        SetEvent(qt_adopted_thread_wakeup);
    }
}
Example #8
0
void Parser::Private::parseError()
{
    Error e;
    QVector<QVector<Frame> > frames;
    XauxWhat currentAux;
    QVector<XauxWhat> auxs;

    int lastAuxWhat = -1;
    while (notAtEnd()) {
        blockingReadNext();
        if (reader.isEndElement())
            break;
        if (reader.isStartElement())
            lastAuxWhat++;
        const QStringRef name = reader.name();
        if (name == QLatin1String("unique")) {
            e.setUnique(parseHex(blockingReadElementText(), QLatin1String("unique")));
        } else if (name == QLatin1String("tid")) {
            e.setTid(parseInt64(blockingReadElementText(), QLatin1String("error/tid")));
        } else if (name == QLatin1String("kind")) { //TODO this is memcheck-specific:
            e.setKind(parseErrorKind(blockingReadElementText()));
        } else if (name == QLatin1String("suppression")) {
            e.setSuppression(parseSuppression());
        } else if (name == QLatin1String("xwhat")) {
            const XWhat xw = parseXWhat();
            e.setWhat(xw.text);
            e.setLeakedBlocks(xw.leakedblocks);
            e.setLeakedBytes(xw.leakedbytes);
            e.setHelgrindThreadId(xw.hthreadid);
        } else if (name == QLatin1String("what")) {
            e.setWhat(blockingReadElementText());
        } else if (name == QLatin1String("xauxwhat")) {
            if (!currentAux.text.isEmpty())
                auxs.push_back(currentAux);
            currentAux = parseXauxWhat();
        } else if (name == QLatin1String("auxwhat")) {
            const QString aux = blockingReadElementText();
            //concatenate multiple consecutive <auxwhat> tags
            if (lastAuxWhat > 1) {
                if (!currentAux.text.isEmpty())
                    auxs.push_back(currentAux);
                currentAux.clear();
                currentAux.text = aux;
            } else {
                if (!currentAux.text.isEmpty())
                    currentAux.text.append(QLatin1Char(' '));
                currentAux.text.append(aux);
            }
            lastAuxWhat = 0;
        } else if (name == QLatin1String("stack")) {
            frames.push_back(parseStack());
        } else if (reader.isStartElement()) {
            reader.skipCurrentElement();
        }
    }

    if (!currentAux.text.isEmpty())
        auxs.push_back(currentAux);

    //if we have less xaux/auxwhats than stacks, prepend empty xauxwhats
    //(the first frame usually has not xauxwhat in helgrind and memcheck)
    while (auxs.size() < frames.size())
        auxs.prepend(XauxWhat());

    QVector<Stack> stacks;
    for (int i = 0; i < auxs.size(); ++i)
        stacks.append(makeStack(auxs[i], frames[i]));
    e.setStacks(stacks);

    emit q->error(e);
}
Example #9
0
AcceptLanguageDialog::AcceptLanguageDialog(const QString &languages, QWidget *parent) : Dialog(parent),
	m_ui(new Ui::AcceptLanguageDialog)
{
	m_ui->setupUi(this);

	m_model = new QStandardItemModel(this);
	m_model->setHorizontalHeaderLabels(QStringList({tr("Name"), tr("Code")}));

	m_ui->languagesViewWidget->setModel(m_model);

	QStringList chosenLanguages(languages.split(QLatin1Char(','), QString::SkipEmptyParts));

	for (int i = 0; i < chosenLanguages.count(); ++i)
	{
		addLanguage(chosenLanguages.at(i).section(QLatin1Char(';'), 0, 0));
	}

	const QList<QLocale> locales(QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::AnyCountry));
	QVector<QPair<QString, QString> > entries;

	for (int i = 0; i < locales.count(); ++i)
	{
		const QLocale locale(locales.at(i));

		if (locale != QLocale::c())
		{
			if (locale.nativeCountryName().isEmpty() || locale.nativeLanguageName().isEmpty())
			{
				entries.append({tr("Unknown [%1]").arg(locale.bcp47Name()), locale.bcp47Name()});
			}
			else
			{
				entries.append({QStringLiteral("%1 - %2 [%3]").arg(locale.nativeLanguageName()).arg(locale.nativeCountryName()).arg(locale.bcp47Name()), locale.bcp47Name()});
			}
		}
	}

	QCollator collator;
	collator.setCaseSensitivity(Qt::CaseInsensitive);

	qSort(entries.begin(), entries.end(), [&](const QPair<QString, QString> &first, const QPair<QString, QString> &second)
	{
		return (collator.compare(first.first, second.first) < 0);
	});

	entries.prepend(QPair<QString, QString>(tr("Any other"), QLatin1String("*")));
	entries.prepend(QPair<QString, QString>(tr("System language (%1 - %2)").arg(QLocale::system().nativeLanguageName()).arg(QLocale::system().nativeCountryName()), QString("system")));

	for (int i = 0; i < entries.count(); ++i)
	{
		m_ui->languagesComboBox->addItem(entries.at(i).first, entries.at(i).second);
	}

	m_ui->moveDownButton->setIcon(ThemesManager::createIcon(QLatin1String("arrow-down")));
	m_ui->moveUpButton->setIcon(ThemesManager::createIcon(QLatin1String("arrow-up")));
	m_ui->languagesComboBox->installEventFilter(this);

	connect(m_ui->moveDownButton, &QToolButton::clicked, m_ui->languagesViewWidget, &ItemViewWidget::moveDownRow);
	connect(m_ui->moveUpButton, &QToolButton::clicked, m_ui->languagesViewWidget, &ItemViewWidget::moveUpRow);
	connect(m_ui->removeButton, &QToolButton::clicked, m_ui->languagesViewWidget, &ItemViewWidget::removeRow);
	connect(m_ui->addButton, &QToolButton::clicked, this, &AcceptLanguageDialog::addNewLanguage);
	connect(m_ui->languagesViewWidget, &ItemViewWidget::canMoveDownChanged, m_ui->moveDownButton, &QToolButton::setEnabled);
	connect(m_ui->languagesViewWidget, &ItemViewWidget::canMoveUpChanged, m_ui->moveUpButton, &QToolButton::setEnabled);
	connect(m_ui->languagesViewWidget, &ItemViewWidget::needsActionsUpdate, this, &AcceptLanguageDialog::updateActions);
}
Example #10
0
static QVector<QPair<QString, QString> > parseAssignments(const QString &code)
{
    QChar c, last;
    enum State { LeftHandSide, RightHandSight, Comment, String, Parentheses } state = LeftHandSide;
    int parenCount = 0;
    State lastState = LeftHandSide; // initialize to make compilers happy
    QChar ignoreEnd[2];
    QString leftHandBuffer, rightHandBuffer;
    QVector<QPair<QString, QString> > assignments;

    for ( int i = 0; i < code.length(); ++i ) {
	    last = c;
	    c = code[ (int) i];

	    if ( state == Comment || state == String || state == Parentheses ) {
	        if ( state == String )
		        APPEND_PARSED_CHAR( lastState );
	            if ( c == '(' && state == Parentheses ) {
		        parenCount++;
		        continue;
	        }
	        if ( !ignoreEnd[1].isNull() ) {
		        if ( last == ignoreEnd[0] && c == ignoreEnd[1] )
		            state = (state == String ? lastState : LeftHandSide);
	        } else if ( c == ignoreEnd[0] ) {
		        if ( state == Parentheses ) {
		            parenCount--;
		            if ( parenCount > 0 )
			        continue;
		        }
    		    state = ( (state == String || state == Parentheses) ? lastState : LeftHandSide );
	        }
	        continue;
        }

	    if ( c == '*' && last == '/' ) {
	        state = Comment;
	        ignoreEnd[0] = '*';
	        ignoreEnd[1] = '/';
	        leftHandBuffer = QString::null;
	        rightHandBuffer = QString::null;
	        continue;
	    } else if ( c == '/' && last == '/' ) {
	        state = Comment;
	        ignoreEnd[0] = '\n';
	        ignoreEnd[1] = QChar::Null;
	        leftHandBuffer = QString::null;
	        rightHandBuffer = QString::null;
	        continue;
	    } else if ( c == '\"' ) {
	        lastState = state;
	        state = String;
	        ignoreEnd[0] = '\"';
	        ignoreEnd[1] = QChar::Null;
	        APPEND_PARSED_CHAR( lastState );
	        continue;
	    } else if ( c == '\'' ) {
	        lastState = state;
	        state = String;
	        ignoreEnd[0] = '\'';
	        ignoreEnd[1] = QChar::Null;
	        APPEND_PARSED_CHAR( lastState );
	        continue;
	    } else if ( c == '(' ) {
	        lastState = state;
	        state = Parentheses;
	        ignoreEnd[0] = ')';
	        ignoreEnd[1] = QChar::Null;
	        parenCount = 1;
	        continue;
	    }

        if ( last.isSpace() ) {
    	    if ( i > 1 && code[ (int)(i-2) ] != '.' && c != '=' && c != ';' && c != '{' && c != '}' && c != '(' && c != ')' ) {
		        if ( state == LeftHandSide )
		            leftHandBuffer = QString::null;
		        else if ( state == RightHandSight )
		            rightHandBuffer = QString::null;
	        }
        }


	    if ( c == ';' || c == '{' || c == '}' ) {
	        if ( state == LeftHandSide ) {
    		    leftHandBuffer = QString::null;
	        } else if ( state == RightHandSight ) {
		        rightHandBuffer = rightHandBuffer.replace( QRegExp( QString::fromLatin1("\\s") ), QString::fromLatin1("") );
		        leftHandBuffer = leftHandBuffer.replace( QRegExp( QString::fromLatin1("\\s") ), QString::fromLatin1("") );
		        QPair<QString, QString> p;
		        p.first = leftHandBuffer;
		        p.second = rightHandBuffer;
		        assignments.prepend( p );
		        leftHandBuffer = QString::null;
		        rightHandBuffer = QString::null;
		        state = LeftHandSide;
		        continue;
	        }
        }

	    if ( c == '=' ) {
	        if ( last == '!' || last == '=' ) {
		        leftHandBuffer = QString::null;
		        rightHandBuffer = QString::null;
		        state = LeftHandSide;
		        continue;
	        }
	        if ( state == RightHandSight ) {
		        leftHandBuffer = QString::null;
		        rightHandBuffer = QString::null;
		        state = LeftHandSide;
	        } else if ( state == LeftHandSide ) {
		        state = RightHandSight;
	        }
    	    continue;
        }

	    APPEND_PARSED_CHAR( state );
    }

    for ( QVector<QPair<QString, QString> >::Iterator it = assignments.begin(); it != assignments.end(); ++it ) {
	    QString key = (*it).first;
	    QString value = (*it).second;
	    QStringList l = value.split('.');
	    QString valuePart;
	    for ( QStringList::ConstIterator vit = l.begin(); vit != l.end(); ++vit ) {
	        if ( !valuePart.isNull() )
		        valuePart += QString::fromLatin1(".");
	        valuePart += *vit;
	        QString replacedValue;
	        int counter = 0;
	        while ( ( replacedValue = resolveValue( valuePart, assignments ) ) != QString::null ) {
		        if( ++counter > 1000 ) // Avoid recursion...
		            return QVector<QPair<QString,QString> >();
    		    valuePart = replacedValue;
	        }
	        (*it).second = valuePart;
        }
    }

    return assignments;
}
LocalListingNetworkReply::LocalListingNetworkReply(const QNetworkRequest &request, QObject *parent) : ListingNetworkReply(request, parent),
	m_offset(0)
{
	setRequest(request);
	open(QIODevice::ReadOnly | QIODevice::Unbuffered);

	QDir directory(request.url().toLocalFile());

	if (!directory.exists() || !directory.isReadable())
	{
		ErrorPageInformation::PageAction reloadAction;
		reloadAction.name = QLatin1String("reloadPage");
		reloadAction.title = QCoreApplication::translate("utils", "Try Again");
		reloadAction.type = ErrorPageInformation::MainAction;

		ErrorPageInformation information;
		information.url = request.url();
		information.actions.append(reloadAction);

		if (directory.isReadable())
		{
			information.description = QStringList(tr("Directory does not exist"));
			information.type = ErrorPageInformation::FileNotFoundError;
		}
		else
		{
			information.title = tr("Directory is not readable");
			information.description = QStringList(tr("Cannot read directory listing"));
		}

		m_content = Utils::createErrorPage(information).toUtf8();

		setError(QNetworkReply::ContentAccessDenied, information.description.first());
		setHeader(QNetworkRequest::ContentTypeHeader, QVariant(QLatin1String("text/html; charset=UTF-8")));
		setHeader(QNetworkRequest::ContentLengthHeader, QVariant(m_content.size()));

		QTimer::singleShot(0, this, [&]()
		{
			emit listingError();
			emit readyRead();
			emit finished();
		});

		return;
	}

	QMimeDatabase mimeDatabase;
	QVector<ListingEntry> entries;
	QVector<NavigationEntry> navigation;
#ifdef Q_OS_WIN32
	const bool isListingDevices(request.url().toLocalFile() == QLatin1String("/"));
	const QFileInfoList rawEntries(isListingDevices ? QDir::drives() : directory.entryInfoList((QDir::AllEntries | QDir::Hidden), (QDir::Name | QDir::DirsFirst)));
#else
	const QFileInfoList rawEntries(directory.entryInfoList((QDir::AllEntries | QDir::Hidden), (QDir::Name | QDir::DirsFirst)));
#endif

	do
	{
		NavigationEntry entry;
#ifdef Q_OS_WIN32
		entry.name = (directory.isRoot() ? directory.canonicalPath() : directory.dirName() + QLatin1Char('/'));
#else
		entry.name = ((directory.isRoot() ? QLatin1String("file://") : QString()) + directory.dirName() + QLatin1Char('/'));
#endif
		entry.url = QUrl::fromUserInput(directory.canonicalPath()).toString();

		navigation.prepend(entry);
	}
	while (directory.cdUp());

#ifdef Q_OS_WIN32
	if (isListingDevices)
	{
		navigation.clear();
	}

	NavigationEntry rootEntry;
	rootEntry.name = QLatin1String("file:///");
	rootEntry.url = QUrl::fromUserInput(QLatin1String("/"));

	navigation.prepend(rootEntry);
#endif

	for (int i = 0; i < rawEntries.count(); ++i)
	{
		if (rawEntries.at(i).fileName() == QLatin1String(".") || rawEntries.at(i).fileName() == QLatin1String(".."))
		{
			continue;
		}

		ListingEntry entry;
		entry.name = rawEntries.at(i).fileName();
		entry.url = QUrl::fromUserInput(rawEntries.at(i).filePath());
		entry.timeModified = rawEntries.at(i).lastModified();
		entry.mimeType = mimeDatabase.mimeTypeForFile(rawEntries.at(i).filePath());
		entry.type = (rawEntries.at(i).isRoot() ? ListingEntry::DriveType : (rawEntries.at(i).isDir() ? ListingEntry::DirectoryType : ListingEntry::FileType));
		entry.size = rawEntries.at(i).size();
		entry.isSymlink = rawEntries.at(i).isSymLink();

#ifdef Q_OS_WIN32
		if (isListingDevices)
		{
			entry.name = rawEntries.at(i).filePath().remove(QLatin1Char('/'));
		}
#endif

		entries.append(entry);
	}

	m_content = createListing(QFileInfo(request.url().toLocalFile()).canonicalFilePath(), navigation, entries);

	setHeader(QNetworkRequest::ContentTypeHeader, QVariant(QLatin1String("text/html; charset=UTF-8")));
	setHeader(QNetworkRequest::ContentLengthHeader, QVariant(m_content.size()));

	QTimer::singleShot(0, this, [&]()
	{
		emit readyRead();
		emit finished();
	});
}
Example #12
0
void OwncloudPropagator::start(const SyncFileItemVector& items)
{
    Q_ASSERT(std::is_sorted(items.begin(), items.end()));

    /* Check and log the transmission checksum type */
    ConfigFile cfg;
    const QString checksumType = cfg.transmissionChecksum();

    /* if the checksum type is empty, it is not sent. No error */
    if( !checksumType.isEmpty() ) {
        if( checksumType == checkSumAdlerC ||
                checksumType == checkSumMD5C    ||
                checksumType == checkSumSHA1C ) {
            qDebug() << "Client sends transmission checksum type" << checksumType;
        } else {
            qWarning() << "Unknown transmission checksum type from config" << checksumType;
        }
    }

    /* This builds all the jobs needed for the propagation.
     * Each directory is a PropagateDirectory job, which contains the files in it.
     * In order to do that we loop over the items. (which are sorted by destination)
     * When we enter a directory, we can create the directory job and push it on the stack. */

    _rootJob.reset(new PropagateDirectory(this));
    QStack<QPair<QString /* directory name */, PropagateDirectory* /* job */> > directories;
    directories.push(qMakePair(QString(), _rootJob.data()));
    QVector<PropagatorJob*> directoriesToRemove;
    QString removedDirectory;
    foreach(const SyncFileItemPtr &item, items) {

        if (!removedDirectory.isEmpty() && item->_file.startsWith(removedDirectory)) {
            // this is an item in a directory which is going to be removed.
            PropagateDirectory *delDirJob = dynamic_cast<PropagateDirectory*>(directoriesToRemove.first());

            if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
                // already taken care of. (by the removal of the parent directory)

                // increase the number of subjobs that would be there.
                if( delDirJob ) {
                    delDirJob->increaseAffectedCount();
                }
                continue;
            } else if (item->_isDirectory
                       && (item->_instruction == CSYNC_INSTRUCTION_NEW
                           || item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE)) {
                // create a new directory within a deleted directory? That can happen if the directory
                // etag was not fetched properly on the previous sync because the sync was aborted
                // while uploading this directory (which is now removed).  We can ignore it.
                if( delDirJob ) {
                    delDirJob->increaseAffectedCount();
                }
                continue;
            } else if (item->_instruction == CSYNC_INSTRUCTION_IGNORE) {
                continue;
            } else if (item->_instruction == CSYNC_INSTRUCTION_RENAME) {
                // all is good, the rename will be executed before the directory deletion
            } else {
                qWarning() << "WARNING:  Job within a removed directory?  This should not happen!"
                           << item->_file << item->_instruction;
            }
        }

        while (!item->destination().startsWith(directories.top().first)) {
            directories.pop();
        }

        if (item->_isDirectory) {
            PropagateDirectory *dir = new PropagateDirectory(this, item);
            dir->_firstJob.reset(createJob(item));

            if (item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE
                    && item->_direction == SyncFileItem::Up) {
                // Skip all potential uploads to the new folder.
                // Processing them now leads to problems with permissions:
                // checkForPermissions() has already run and used the permissions
                // of the file we're about to delete to decide whether uploading
                // to the new dir is ok...
                foreach(const SyncFileItemPtr &item2, items) {
                    if (item2->destination().startsWith(item->destination() + "/")) {
                        item2->_instruction = CSYNC_INSTRUCTION_NONE;
                        _anotherSyncNeeded = true;
                    }
                }
            }

            if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
                // We do the removal of directories at the end, because there might be moves from
                // these directories that will happen later.
                directoriesToRemove.prepend(dir);
                removedDirectory = item->_file + "/";

                // We should not update the etag of parent directories of the removed directory
                // since it would be done before the actual remove (issue #1845)
                // NOTE: Currently this means that we don't update those etag at all in this sync,
                //       but it should not be a problem, they will be updated in the next sync.
                for (int i = 0; i < directories.size(); ++i) {
                    directories[i].second->_item->_should_update_metadata = false;
                }
            } else {
                PropagateDirectory* currentDirJob = directories.top().second;
                currentDirJob->append(dir);
            }
            directories.push(qMakePair(item->destination() + "/" , dir));
        } else if (PropagateItemJob* current = createJob(item)) {
Example #13
0
void tst_ExceptionSafety::exceptionVector() {

    {
        QVector<FlexibleThrowerSmall> vector;
        QVector<FlexibleThrowerSmall> vector2;
        QVector<FlexibleThrowerSmall> vector3;

        for (int i = 0; i<10; i++)
            vector.append( FlexibleThrowerSmall(i) );

        try {
            throwType = ThrowAtCopy;
            vector.append( FlexibleThrowerSmall(10));
        } catch (...) {
        }
        QCOMPARE( vector.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            vector.prepend( FlexibleThrowerSmall(10));
        } catch (...) {
        }
        QCOMPARE( vector.at(0).value(), 0 );
        QCOMPARE( vector.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            vector.insert( 8, FlexibleThrowerSmall(10));
        } catch (...) {
        }
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.at(8).value(), 8 );
        QCOMPARE( vector.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            vector3 = vector;
        } catch (...) {
        }
        QCOMPARE( vector.at(0).value(), 0 );
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );
        QCOMPARE( vector3.at(0).value(), 0 );
        QCOMPARE( vector3.at(7).value(), 7 );
        QCOMPARE( vector3.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            vector3.append( FlexibleThrowerSmall(11) );
        } catch (...) {
        }
        QCOMPARE( vector.at(0).value(), 0 );
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );
        QCOMPARE( vector3.at(0).value(), 0 );
        QCOMPARE( vector3.at(7).value(), 7 );

        try {
            vector2.clear();
            vector2.append( FlexibleThrowerSmall(11));
            throwType = ThrowAtCopy;
            vector3 = vector+vector2;
        } catch (...) {
        }
        QCOMPARE( vector.at(0).value(), 0 );
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );

        // check that copy on write works atomar
        vector2.clear();
        vector2.append( FlexibleThrowerSmall(11));
        vector3 = vector+vector2;
        try {
            throwType = ThrowAtCreate;
            vector3[7]=FlexibleThrowerSmall(12);
        } catch (...) {
        }
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );
        QCOMPARE( vector3.at(7).value(), 7 );
        QCOMPARE( vector3.size(), 11 );

        try {
            throwType = ThrowAtCreate;
            vector.resize(15);
        } catch (...) {
        }
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );

        try {
            throwType = ThrowAtCreate;
            vector.resize(15);
        } catch (...) {
        }
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );

        try {
            throwType = ThrowLater;
            vector.fill(FlexibleThrowerSmall(1), 15);
        } catch (...) {
        }
        QCOMPARE( vector.at(0).value(), 0 );
        QCOMPARE( vector.size(), 10 );


    }
    QCOMPARE(objCounter, 0 ); // check that every object has been freed
}
Example #14
0
bool DiacriticRules::on_match()
{
    double ambiguity_reduction = 0.0;
    int least_ambiguity_position = -1;

    /** Number of Morphemes **/
    int number_of_morphemes = 0;

    /** letter count of unvocalized word **/
    int length = 0;

    QString vocalizedWord;
    QString unvocalizedWord;
    QVector<QString> prefixPOSs;
    QVector<QString> prefixes;
    QString stemPOS;
    QVector<QString> suffixPOSs;
    QVector<QString> suffixes;

    int prefix_length = 0;
    /** letter count of stem **/
    int stem_length = 0;
    int suffix_length = 0;

    /** Get vocalized and unvocalized words **/
    int prefix_infos_size = prefix_infos->size();
    for (int i= 0; i<prefix_infos_size;i++) {
        minimal_item_info & pre = (*prefix_infos)[i];
        if(!(pre.raw_data.isEmpty())) {
            number_of_morphemes++;
            vocalizedWord.append(pre.raw_data);
        }
    }
    prefix_length = removeDiacritics(vocalizedWord).count();

    number_of_morphemes++;
    vocalizedWord.append(stem_info->raw_data);
    stem_length = removeDiacritics(stem_info->raw_data).count();

    int suffix_infos_size = suffix_infos->size();
    for (int i=0;i<suffix_infos_size;i++) {
        minimal_item_info & suff = (*suffix_infos)[i];
        if(!(suff.raw_data.isEmpty())) {
            number_of_morphemes++;
            vocalizedWord.append(suff.raw_data);
        }
    }

    unvocalizedWord = removeDiacritics(vocalizedWord);

    /** Unvocalized word Character Count **/
    length = unvocalizedWord.count();
    suffix_length = length - (prefix_length + stem_length);

    /** Ambiguity of the unvocalized word **/
    int unvocalizedAmbiguity = 0;
    WordAmbiguity wa(&unvocalizedWord, &unvocalizedAmbiguity);
    wa();

    /** Discard this morphological solution if the unvocalized word is not ambiguous (has 1 morpho. solution) **/
    if(unvocalizedAmbiguity < 2) {
        return true;
    }

    /// Select required morphological features

    /** Prefix Features **/
    int j = 0;
    for (int i = (prefix_infos_size-1); (i>=0) && (j<4);i--) {
        minimal_item_info & pre = (*prefix_infos)[i];
        if(pre.POS.isEmpty() && pre.raw_data.isEmpty()) {
            continue;
        }

        QStringList pre_poss = pre.POS.split('/');
        if(pre_poss.count() != 2) {
            continue;
        }
        QString unvoc_pre_data = removeDiacritics(pre.raw_data);
        if(!(unvoc_pre_data.isEmpty())) {
            prefixes.prepend(unvoc_pre_data);
        }
        if(!(pre_poss[1].isEmpty())) {
            prefixPOSs.prepend(pre_poss[1]);
        }
        j++;
    }

    while(prefixes.count() < 4) {
        prefixes.prepend("EPRE");
    }

    while(prefixPOSs.count() < 4) {
        prefixPOSs.prepend("EPREPOS");
    }

    /** Stem Features **/
    minimal_item_info & stem = *stem_info;
    //stem_length = removeDiacritics(stem.raw_data).count();
    QStringList stem_poss = stem.POS.split('/');
    if(stem_poss.count() != 2) {
        return true;
    }
    stemPOS = stem_poss[1];

    /** Suffix Features **/
    j = 0;
    for (int i=0;(i<suffix_infos_size) && (j<4);i++) {
        minimal_item_info & suff = (*suffix_infos)[i];
        if(suff.POS.isEmpty() && suff.raw_data.isEmpty()) {
            continue;
        }

        QStringList suff_poss = suff.POS.split('/');
        if(suff_poss.count() != 2) {
            continue;
        }
        QString unvoc_suf_data = removeDiacritics(suff.raw_data);
        if(!(unvoc_suf_data.isEmpty())) {
            suffixes.append(unvoc_suf_data);
        }
        if(!(suff_poss[1].isEmpty())) {
            suffixPOSs.append(suff_poss[1]);
        }
        j++;
    }

    while(suffixes.count() < 4) {
        suffixes.append("ESUF");
    }

    while(suffixPOSs.count() < 4) {
        suffixPOSs.append("ESUFPOS");
    }

    /// Detach diacritics from raw_data and store in separate structure
    int diacritic_Counter = 0;
    QVector<QVector<QChar> > wordDiacritics(length);
    int letterIndex = 0;
    for(int i=1; i<vocalizedWord.count(); i++) {
        QChar currentLetter= vocalizedWord[i];
        if(isDiacritic(currentLetter)) {
            wordDiacritics[letterIndex].append(currentLetter);
            diacritic_Counter++;
        }
        else {
            letterIndex++;
        }
    }

    if(diacritic_Counter == 0) {
        return true;
    }

    /// Get the number of solutions for each solution with one diacritic
    /// Select diacritic position leastambiguous = least number of morphological solutions
    QVector<QVector<int> > diacriticAmbiguity(length);
    int least_ambiguity = unvocalizedAmbiguity + 1;
    int diacritic_Index = -1;
    for(int i=0; i< wordDiacritics.count(); i++) {
        for(j=0; j< wordDiacritics.at(i).count(); j++) {
            QString one_diacritic_word = unvocalizedWord;
            one_diacritic_word.insert(i+1,wordDiacritics[i][j]);

            int one_diacritic_Ambiguity = 0;
            WordAmbiguity wa(&one_diacritic_word, &one_diacritic_Ambiguity);
            wa();

            if(one_diacritic_Ambiguity == 0) {
                diacriticAmbiguity[i].append(unvocalizedAmbiguity);
            }
            else {
                diacriticAmbiguity[i].append(one_diacritic_Ambiguity);
            }

            if(diacriticAmbiguity[i][j] <  least_ambiguity) {
                least_ambiguity = diacriticAmbiguity[i][j];
                least_ambiguity_position = i;
                diacritic_Index = j;
            }
        }
    }

    /** This weirdly happens when a word partial diacritics has ambiguity more than the unvocalized word (ex. dAn) **/
    if((least_ambiguity_position == -1) || (diacritic_Index == -1)) {
        if(number_of_solutions == -1) {
            return true;
        }
        else if(solution_counter != number_of_solutions) {
            solution_counter++;
            return true;
        }
        else {
            return false;
        }
    }

    ambiguity_reduction = ((unvocalizedAmbiguity- diacriticAmbiguity[least_ambiguity_position][diacritic_Index]) * 1.0) / unvocalizedAmbiguity;

    /** Filter data to extract high ambiguity reduction instances **/

    if(ambiguity_reduction < 0.667) {
        if(number_of_solutions == -1) {
            return true;
        }
        else if(solution_counter != number_of_solutions) {
            solution_counter++;
            return true;
        }
        else {
            return false;
        }
    }
    filtered_items++;

    /** Print/Use data **/

    theSarf->out << number_of_morphemes << "  "
            << length << "  "
            << stem_length << "  ";

    //    prefixPOSs
    for(int i=0; i<prefixPOSs.count(); i++) {
        theSarf->out << prefixPOSs[i] << "  ";
    }

    //    prefixes
    for(int i=0; i< prefixes.count(); i++) {
        theSarf->out << prefixes[i] << "  ";
    }

    //    stemPOS
    theSarf->out << stemPOS << "  ";

    //    suffixPOSs
    for(int i=0; i<suffixPOSs.count(); i++) {
        theSarf->out << suffixPOSs[i] << "  ";
    }

    //    suffixes
    for(int i=0; i<suffixes.count(); i++) {
        theSarf->out << suffixes[i] << "  ";
    }

    //    least_ambiguity_position
    //    prefixs , prefixm, prefixe , stems , stemm, steme , suffixs , suffixm, suffixe
    //theSarf->out << least_ambiguity_position << "  ";
    QString diacritic_position;

    if((prefix_length != 0) && (least_ambiguity_position == 0)) {
        diacritic_position = "prefixs";
    }
    else if((prefix_length != 0) && (least_ambiguity_position > 0) && (least_ambiguity_position < (prefix_length-1))) {
        diacritic_position = "prefixm";
    }
    else if((prefix_length != 0) && (least_ambiguity_position == (prefix_length-1))) {
        diacritic_position = "prefixe";
    }
    else if(least_ambiguity_position == prefix_length) {
        diacritic_position = "stems";
    }
    else if((least_ambiguity_position > (prefix_length)) && (least_ambiguity_position < (prefix_length + stem_length - 1))) {
        diacritic_position = "stemm";
    }
    else if(least_ambiguity_position == (prefix_length + stem_length - 1)) {
        diacritic_position = "steme";
    }
    else if((suffix_length != 0) && (least_ambiguity_position == (prefix_length + stem_length))) {
        diacritic_position = "suffixs";
    }
    else if((suffix_length != 0) && (least_ambiguity_position > (prefix_length + stem_length)) && (least_ambiguity_position < (length - 1))) {
        diacritic_position = "suffixm";
    }
    else if((suffix_length != 0) && (least_ambiguity_position == (length -1))) {
        diacritic_position = "suffixe";
    }
    else {
        cout << "Couldn't set diacritic position!" << endl;
        return false;
    }
    theSarf->out << diacritic_position << '\n';

    //    ambiguity_reduction
    //theSarf->out << ambiguity_reduction << '\n';

    /** Check for number of solutions requested **/
    if(number_of_solutions == -1) {
        return true;
    }
    else if(solution_counter != number_of_solutions) {
        solution_counter++;
        return true;
    }
    else {
        return false;
    }
};
Example #15
0
KisImageBuilder_Result CSVSaver::encode(const QUrl &uri,const QString &filename)
{
    int idx;
    int start, end;
    KisNodeSP node;
    QByteArray ba;
    KisKeyframeSP keyframe;
    QVector<CSVLayerRecord*> layers;

    KisImageAnimationInterface *animation = m_image->animationInterface();

    //open the csv file for writing
    QFile f(uri.toLocalFile());
    if (!f.open(QIODevice::WriteOnly)) {
        return KisImageBuilder_RESULT_NOT_LOCAL;
    }

    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

    //DataStream instead of TextStream for correct line endings
    QDataStream stream(&f);

    QString path = filename;

    if (path.right(4).toUpper() == ".CSV")
        path = path.left(path.size() - 4);

    path.append(".frames");

    //create directory

    QDir dir(path);
    if (!dir.exists()) {
        dir.mkpath(".");
    }
    //according to the QT docs, the slash is a universal directory separator
    path.append("/");

    m_image->lock();
    node = m_image->rootLayer()->firstChild();

    //TODO: correct handling of the layer tree.
    //for now, only top level paint layers are saved

    idx = 0;

    while (node) {
        if (node->inherits("KisPaintLayer")) {
            KisPaintLayer* paintLayer = dynamic_cast<KisPaintLayer*>(node.data());
            CSVLayerRecord* layerRecord = new CSVLayerRecord();
            layers.prepend(layerRecord); //reverse order!

            layerRecord->name = paintLayer->name();
            layerRecord->name.replace(QRegExp("[\"\\r\\n]"), "_");

            if (layerRecord->name.isEmpty())
                layerRecord->name= QString("Unnamed-%1").arg(idx);

            layerRecord->visible = (paintLayer->visible()) ? 1 : 0;
            layerRecord->density = (float)(paintLayer->opacity()) / OPACITY_OPAQUE_U8;
            layerRecord->blending = convertToBlending(paintLayer->compositeOpId());
            layerRecord->layer = paintLayer;
            layerRecord->channel = paintLayer->projection()->keyframeChannel();
            layerRecord->last = "";
            layerRecord->frame = 0;
            idx++;
        }
        node = node->nextSibling();
    }

    KisTimeRange range = animation->fullClipRange();

    start = (range.isValid()) ? range.start() : 0;

    if (!range.isInfinite()) {
        end = range.end();

        if (end < start) end = start;
    } else {
        //undefined length, searching for the last keyframe
        end = start;

        for (idx = 0; idx < layers.size(); idx++) {
            keyframe = layers.at(idx)->channel->lastKeyframe();

            if ( (!keyframe.isNull()) && (keyframe->time() > end) )
                end = keyframe->time();
        }
    }

    //create temporary doc for exporting
    QScopedPointer<KisDocument> exportDoc(KisPart::instance()->createDocument());
    createTempImage(exportDoc.data());

    KisImageBuilder_Result retval= KisImageBuilder_RESULT_OK;

    if (!m_batchMode) {
        emit m_doc->statusBarMessage(i18n("Saving CSV file..."));
        emit m_doc->sigProgress(0);
        connect(m_doc, SIGNAL(sigProgressCanceled()), this, SLOT(cancel()));
    }
    int frame = start;
    int step = 0;

    do {
        qApp->processEvents();

        if (m_stop) {
            retval = KisImageBuilder_RESULT_CANCEL;
            break;
        }

        switch(step) {

        case 0 :    //first row
            if (f.write("UTF-8, TVPaint, \"CSV 1.0\"\r\n") < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
            }
            break;

        case 1 :    //scene header names
            if (f.write("Project Name, Width, Height, Frame Count, Layer Count, Frame Rate, Pixel Aspect Ratio, Field Mode\r\n") < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
            }
            break;

        case 2 :    //scene header values
            ba = QString("\"%1\", ").arg(m_image->objectName()).toUtf8();
            if (f.write(ba.data()) < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }
            ba = QString("%1, %2, ").arg(m_image->width()).arg(m_image->height()).toUtf8();
            if (f.write(ba.data()) < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }

            ba = QString("%1, %2, ").arg(end - start + 1).arg(layers.size()).toUtf8();
            if (f.write(ba.data()) < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }
            //the framerate is an integer here
            ba = QString("%1, ").arg((double)(animation->framerate()),0,'f',6).toUtf8();
            if (f.write(ba.data()) < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }
            ba = QString("%1, Progressive\r\n").arg((double)(m_image->xRes() / m_image->yRes()),0,'f',6).toUtf8();
            if (f.write(ba.data()) < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }
            break;

        case 3 :    //layer header values
            if (f.write("#Layers") < 0) {          //Layers
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }

            for (idx = 0; idx < layers.size(); idx++) {
                ba = QString(", \"%1\"").arg(layers.at(idx)->name).toUtf8();
                if (f.write(ba.data()) < 0)
                    break;
            }
            break;

        case 4 :
            if (f.write("\r\n#Density") < 0) {     //Density
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }
            for (idx = 0; idx < layers.size(); idx++) {
                ba = QString(", %1").arg((double)(layers.at(idx)->density), 0, 'f', 6).toUtf8();
                if (f.write(ba.data()) < 0)
                    break;
            }
            break;

        case 5 :
            if (f.write("\r\n#Blending") < 0) {     //Blending
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }
            for (idx = 0; idx < layers.size(); idx++) {
                ba = QString(", \"%1\"").arg(layers.at(idx)->blending).toUtf8();
                if (f.write(ba.data()) < 0)
                    break;
            }
            break;

        case 6 :
            if (f.write("\r\n#Visible") < 0) {     //Visible
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }
            for (idx = 0; idx < layers.size(); idx++) {
                ba = QString(", %1").arg(layers.at(idx)->visible).toUtf8();
                if (f.write(ba.data()) < 0)
                    break;
            }
            if (idx < layers.size()) {
                retval = KisImageBuilder_RESULT_FAILURE;
            }
            break;

        default :    //frames

            if (frame > end) {
                if (f.write("\r\n") < 0)
                    retval = KisImageBuilder_RESULT_FAILURE;

                step = 8;
                break;
            }

            ba = QString("\r\n#%1").arg(frame, 5, 10, QChar('0')).toUtf8();
            if (f.write(ba.data()) < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }

            for (idx = 0; idx < layers.size(); idx++) {
                CSVLayerRecord *layer = layers.at(idx);
                keyframe = layer->channel->keyframeAt(frame);

                if (!keyframe.isNull()) {
                    if (!m_batchMode) {
                        emit m_doc->sigProgress(((frame - start) * layers.size() + idx) * 100 /
                                                ((end - start) * layers.size()));
                    }
                    retval = getLayer(layer, exportDoc.data(), keyframe, path, frame, idx);

                    if (retval != KisImageBuilder_RESULT_OK)
                        break;
                }
                ba = QString(", \"%1\"").arg(layer->last).toUtf8();

                if (f.write(ba.data()) < 0)
                    break;
            }
            if (idx < layers.size())
                retval = KisImageBuilder_RESULT_FAILURE;

            frame++;
            step = 6; //keep step here
            break;
        }
        step++;
    } while((retval == KisImageBuilder_RESULT_OK) && (step < 8));

    m_image->unlock();

    qDeleteAll(layers);
    f.close();

    if (!m_batchMode) {
        disconnect(m_doc, SIGNAL(sigProgressCanceled()), this, SLOT(cancel()));
        emit m_doc->sigProgress(100);
        emit m_doc->clearStatusBarMessage();
    }
    QApplication::restoreOverrideCursor();
    return retval;
}