diff --git a/src/actionproxy.h b/src/actionproxy.h --- a/src/actionproxy.h +++ b/src/actionproxy.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -43,25 +43,34 @@ Q_OBJECT public: - ActionProxy(QObject* parent,QObject* receiver=0,const char* slot=0); + ActionProxy(QObject* parent, QObject* receiver = 0, const char* slot = 0); ~ActionProxy(); void registerAction(QAction*); void unregisterAction(/*QAction**/); - void setStatusTip(const QString& st){m_statusTip=st;}//for TM suggestions - QKeySequence shortcut(){return m_keySequence;};//for TM suggestions + void setStatusTip(const QString& st) + { + m_statusTip = st; //for TM suggestions + } + QKeySequence shortcut() + { + return m_keySequence; + };//for TM suggestions public slots: void setDisabled(bool); - void setEnabled(bool enabled){setDisabled(!enabled);} + void setEnabled(bool enabled) + { + setDisabled(!enabled); + } void setChecked(bool); private slots: void handleToggled(bool); signals: - void triggered(bool=false); + void triggered(bool = false); void toggled(bool); private: @@ -74,16 +83,19 @@ #endif -class StatusBarProxy: public QMap +class StatusBarProxy: public QMap { public: - StatusBarProxy():m_currentStatusBar(0){} - ~StatusBarProxy(){} + StatusBarProxy(): m_currentStatusBar(0) {} + ~StatusBarProxy() {} - void insert(int,const QString&); + void insert(int, const QString&); void registerStatusBar(QStatusBar*, const QVector& statusBarLabels); - void unregisterStatusBar(){m_currentStatusBar=0;} + void unregisterStatusBar() + { + m_currentStatusBar = 0; + } private: QStatusBar* m_currentStatusBar; diff --git a/src/actionproxy.cpp b/src/actionproxy.cpp --- a/src/actionproxy.cpp +++ b/src/actionproxy.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -29,15 +29,15 @@ #include -ActionProxy::ActionProxy(QObject* parent,QObject* receiver,const char* slot) - : QObject(parent) - , m_currentAction(0) - , m_disabled(false) - , m_checked(false) +ActionProxy::ActionProxy(QObject* parent, QObject* receiver, const char* slot) + : QObject(parent) + , m_currentAction(0) + , m_disabled(false) + , m_checked(false) // , m_checkable(false) { if (receiver) - connect(this,SIGNAL(triggered(bool)),receiver,slot); + connect(this, SIGNAL(triggered(bool)), receiver, slot); connect(this, &ActionProxy::toggled, this, &ActionProxy::handleToggled); } @@ -49,68 +49,67 @@ void ActionProxy::registerAction(QAction* a) { - if (a==m_currentAction) + if (a == m_currentAction) return; - m_currentAction=a; + m_currentAction = a; a->setChecked(m_checked); a->setDisabled(m_disabled); a->setStatusTip(m_statusTip); - m_keySequence=a->shortcut(); + m_keySequence = a->shortcut(); - connect(a,SIGNAL(triggered(bool)),this,SIGNAL(triggered(bool))); - connect(a,SIGNAL(toggled(bool)),this,SIGNAL(toggled(bool))); + connect(a, SIGNAL(triggered(bool)), this, SIGNAL(triggered(bool))); + connect(a, SIGNAL(toggled(bool)), this, SIGNAL(toggled(bool))); } void ActionProxy::unregisterAction(/*QAction**/) { - disconnect(m_currentAction,SIGNAL(triggered(bool)),this,SIGNAL(triggered(bool))); - disconnect(m_currentAction,SIGNAL(toggled(bool)),this,SIGNAL(toggled(bool))); + disconnect(m_currentAction, SIGNAL(triggered(bool)), this, SIGNAL(triggered(bool))); + disconnect(m_currentAction, SIGNAL(toggled(bool)), this, SIGNAL(toggled(bool))); m_currentAction->setStatusTip(QString()); - m_currentAction=0; + m_currentAction = 0; } void ActionProxy::handleToggled(bool checked) { - m_checked=checked; + m_checked = checked; } void ActionProxy::setDisabled(bool disabled) { if (m_currentAction) m_currentAction->setDisabled(disabled); - m_disabled=disabled; + m_disabled = disabled; } void ActionProxy::setChecked(bool checked) { if (m_currentAction) m_currentAction->setChecked(checked); //handleToggled is called implicitly via signal/slot mechanism else - m_checked=checked; + m_checked = checked; } #endif -void StatusBarProxy::insert(int key,const QString& str) +void StatusBarProxy::insert(int key, const QString& str) { if (m_currentStatusBar) - if (keysetText(str); - QMap::insert(key,str); + if (key < m_statusBarLabels.size()) m_statusBarLabels.at(key)->setText(str); + QMap::insert(key, str); } void StatusBarProxy::registerStatusBar(QStatusBar* bar, const QVector& statusBarLabels) { - m_currentStatusBar=bar; - m_statusBarLabels=statusBarLabels; - for (int i=0;isetText(QString()); - QMap::const_iterator i = constBegin(); - while (i != constEnd()) - { - if (i.key()setText(i.value()); + QMap::const_iterator i = constBegin(); + while (i != constEnd()) { + if (i.key() < statusBarLabels.size()) statusBarLabels.at(i.key())->setText(i.value()); ++i; } } diff --git a/src/alttransview.h b/src/alttransview.h --- a/src/alttransview.h +++ b/src/alttransview.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -29,24 +29,27 @@ #include "pos.h" #include "alttrans.h" #include -namespace TM{class TextBrowser;} +namespace TM +{ +class TextBrowser; +} class Catalog; class QAction; class AltTransView: public QDockWidget { Q_OBJECT public: - AltTransView(QWidget*,Catalog*,const QVector&); + AltTransView(QWidget*, Catalog*, const QVector&); ~AltTransView(); public slots: void slotNewEntryDisplayed(const DocPosition&); void fileLoaded(); void attachAltTransFile(const QString&); - void addAlternateTranslation(int entry, const QString&, bool temp=true); + void addAlternateTranslation(int entry, const QString&, bool temp = true); private slots: //void contextMenu(const QPoint & pos); diff --git a/src/alttransview.cpp b/src/alttransview.cpp --- a/src/alttransview.cpp +++ b/src/alttransview.cpp @@ -46,12 +46,12 @@ #include #include -AltTransView::AltTransView(QWidget* parent, Catalog* catalog,const QVector& actions) - : QDockWidget ( i18nc("@title:window","Alternate Translations"), parent) +AltTransView::AltTransView(QWidget* parent, Catalog* catalog, const QVector& actions) + : QDockWidget(i18nc("@title:window", "Alternate Translations"), parent) , m_browser(new TM::TextBrowser(this)) , m_catalog(catalog) - , m_normTitle(i18nc("@title:window","Alternate Translations")) - , m_hasInfoTitle(m_normTitle+QStringLiteral(" [*]")) + , m_normTitle(i18nc("@title:window", "Alternate Translations")) + , m_hasInfoTitle(m_normTitle + QStringLiteral(" [*]")) , m_hasInfo(false) , m_everShown(false) , m_actions(actions) @@ -71,15 +71,14 @@ #ifndef NOKDE KConfig config; - KConfigGroup group(&config,"AltTransView"); - m_everShown=group.readEntry("EverShown",false); + KConfigGroup group(&config, "AltTransView"); + m_everShown = group.readEntry("EverShown", false); #endif - QSignalMapper* signalMapper=new QSignalMapper(this); - int i=m_actions.size(); - while(--i>=0) - { + QSignalMapper* signalMapper = new QSignalMapper(this); + int i = m_actions.size(); + while (--i >= 0) { connect(m_actions.at(i), &QAction::triggered, signalMapper, QOverload<>::of(&QSignalMapper::map)); signalMapper->setMapping(m_actions.at(i), i); } @@ -95,7 +94,7 @@ void AltTransView::dragEnterEvent(QDragEnterEvent* event) { - if(event->mimeData()->hasUrls() && Catalog::extIsSupported(event->mimeData()->urls().first().path())) + if (event->mimeData()->hasUrls() && Catalog::extIsSupported(event->mimeData()->urls().first().path())) event->acceptProposedAction(); } @@ -105,217 +104,204 @@ attachAltTransFile(event->mimeData()->urls().first().toLocalFile()); //update - m_prevEntry.entry=-1; + m_prevEntry.entry = -1; QTimer::singleShot(0, this, &AltTransView::process); } void AltTransView::attachAltTransFile(const QString& path) { - MergeCatalog* altCat=new MergeCatalog(m_catalog, m_catalog, /*saveChanges*/false); + MergeCatalog* altCat = new MergeCatalog(m_catalog, m_catalog, /*saveChanges*/false); altCat->loadFromUrl(path); m_catalog->attachAltTransCatalog(altCat); } void AltTransView::addAlternateTranslation(int entry, const QString& trans, bool temp) { AltTrans altTrans; - altTrans.target=trans; + altTrans.target = trans; m_catalog->attachAltTrans(entry, altTrans); - m_prevEntry=DocPos(); + m_prevEntry = DocPos(); QTimer::singleShot(0, this, &AltTransView::process); } void AltTransView::fileLoaded() { - m_prevEntry.entry=-1; - QString absPath=m_catalog->url(); - QString relPath=QDir(Project::instance()->projectDir()).relativeFilePath(absPath); - - QFileInfo info(Project::instance()->altTransDir()%'/'%relPath); - if (info.canonicalFilePath()!=absPath && info.exists()) + m_prevEntry.entry = -1; + QString absPath = m_catalog->url(); + QString relPath = QDir(Project::instance()->projectDir()).relativeFilePath(absPath); + + QFileInfo info(Project::instance()->altTransDir() % '/' % relPath); + if (info.canonicalFilePath() != absPath && info.exists()) attachAltTransFile(info.canonicalFilePath()); else - qCWarning(LOKALIZE_LOG)<<"alt trans file doesn't exist:"<altTransDir()%'/'%relPath; + qCWarning(LOKALIZE_LOG) << "alt trans file doesn't exist:" << Project::instance()->altTransDir() % '/' % relPath; } void AltTransView::slotNewEntryDisplayed(const DocPosition& pos) { - m_entry=DocPos(pos); + m_entry = DocPos(pos); QTimer::singleShot(0, this, &AltTransView::process); } void AltTransView::process() { - if (m_entry==m_prevEntry) return; - if (m_catalog->numberOfEntries()<=m_entry.entry) + if (m_entry == m_prevEntry) return; + if (m_catalog->numberOfEntries() <= m_entry.entry) return;//because of Qt::QueuedConnection - m_prevEntry=m_entry; + m_prevEntry = m_entry; m_browser->clear(); m_entryPositions.clear(); - const QVector& entries=m_catalog->altTrans(m_entry.toDocPosition()); - m_entries=entries; + const QVector& entries = m_catalog->altTrans(m_entry.toDocPosition()); + m_entries = entries; - if (entries.isEmpty()) - { - if (m_hasInfo) - { - m_hasInfo=false; + if (entries.isEmpty()) { + if (m_hasInfo) { + m_hasInfo = false; setWindowTitle(m_normTitle); } return; } - if (!m_hasInfo) - { - m_hasInfo=true; + if (!m_hasInfo) { + m_hasInfo = true; setWindowTitle(m_hasInfoTitle); } - if(!isVisible() && !Settings::altTransViewEverShownWithData()) - { - if (KMessageBox::questionYesNo(this,i18n("There is useful data available in Alternate Translations view.\n\n" - "For Gettext PO files it displays difference between current source text " - "and the source text corresponding to the fuzzy translation found by msgmerge when updating PO based on POT template.\n\n" - "Do you want to show the view with the data?"), m_normTitle)==KMessageBox::Yes) - show(); + if (!isVisible() && !Settings::altTransViewEverShownWithData()) { + if (KMessageBox::questionYesNo(this, i18n("There is useful data available in Alternate Translations view.\n\n" + "For Gettext PO files it displays difference between current source text " + "and the source text corresponding to the fuzzy translation found by msgmerge when updating PO based on POT template.\n\n" + "Do you want to show the view with the data?"), m_normTitle) == KMessageBox::Yes) + show(); Settings::setAltTransViewEverShownWithData(true); } - CatalogString source=m_catalog->sourceWithTags(m_entry.toDocPosition()); + CatalogString source = m_catalog->sourceWithTags(m_entry.toDocPosition()); QTextBlockFormat blockFormatBase; QTextBlockFormat blockFormatAlternate; blockFormatAlternate.setBackground(QPalette().alternateBase()); QTextCharFormat noncloseMatchCharFormat; QTextCharFormat closeMatchCharFormat; closeMatchCharFormat.setFontWeight(QFont::Bold); - int i=0; - int limit=entries.size(); - forever - { - const AltTrans& entry=entries.at(i); + int i = 0; + int limit = entries.size(); + forever { + const AltTrans& entry = entries.at(i); - QTextCursor cur=m_browser->textCursor(); + QTextCursor cur = m_browser->textCursor(); QString html; html.reserve(1024); - if (!entry.source.isEmpty()) - { - html+=QStringLiteral("

"); + if (!entry.source.isEmpty()) { + html += QStringLiteral("

"); - QString result=userVisibleWordDiff(entry.source.string, source.string,Project::instance()->accel(),Project::instance()->markup()).toHtmlEscaped(); + QString result = userVisibleWordDiff(entry.source.string, source.string, Project::instance()->accel(), Project::instance()->markup()).toHtmlEscaped(); //result.replace("&","&"); //result.replace("<","<"); //result.replace(">",">"); - result.replace(QStringLiteral("{KBABELADD}"),QStringLiteral("")); - result.replace(QStringLiteral("{/KBABELADD}"),QStringLiteral("")); - result.replace(QStringLiteral("{KBABELDEL}"),QStringLiteral("")); - result.replace(QStringLiteral("{/KBABELDEL}"),QStringLiteral("")); - result.replace(QStringLiteral("\\n"),QStringLiteral("\\n

")); - - html+=result; - html+=QStringLiteral("
"); + result.replace(QStringLiteral("{KBABELADD}"), QStringLiteral("")); + result.replace(QStringLiteral("{/KBABELADD}"), QStringLiteral("")); + result.replace(QStringLiteral("{KBABELDEL}"), QStringLiteral("")); + result.replace(QStringLiteral("{/KBABELDEL}"), QStringLiteral("")); + result.replace(QStringLiteral("\\n"), QStringLiteral("\\n

")); + + html += result; + html += QStringLiteral("
"); cur.insertHtml(html); html.clear(); } - if (!entry.target.isEmpty()) - { - if (Q_LIKELY( isetStatusTip(entry.target.string); - html+=QString(QStringLiteral("[%1] ")).arg(m_actions.at(i)->shortcut().toString(QKeySequence::NativeText)); - } - else - html+=QStringLiteral("[ - ] "); + html += QString(QStringLiteral("[%1] ")).arg(m_actions.at(i)->shortcut().toString(QKeySequence::NativeText)); + } else + html += QStringLiteral("[ - ] "); cur.insertText(html); html.clear(); - insertContent(cur,entry.target); + insertContent(cur, entry.target); } - m_entryPositions.insert(cur.anchor(),i); + m_entryPositions.insert(cur.anchor(), i); - html+=i?QStringLiteral("

"):QStringLiteral("

"); + html += i ? QStringLiteral("

") : QStringLiteral("

"); cur.insertHtml(html); - if (Q_UNLIKELY( ++i>=limit )) + if (Q_UNLIKELY(++i >= limit)) break; - cur.insertBlock(i%2?blockFormatAlternate:blockFormatBase); + cur.insertBlock(i % 2 ? blockFormatAlternate : blockFormatBase); } #ifndef NOKDE - if (!m_everShown) - { - m_everShown=true; + if (!m_everShown) { + m_everShown = true; show(); KConfig config; - KConfigGroup group(&config,"AltTransView"); - group.writeEntry("EverShown",true); + KConfigGroup group(&config, "AltTransView"); + group.writeEntry("EverShown", true); } #endif } bool AltTransView::event(QEvent *event) { - if (event->type()==QEvent::ToolTip) - { + if (event->type() == QEvent::ToolTip) { QHelpEvent *helpEvent = static_cast(event); - - if (m_entryPositions.isEmpty()) - { - QString tooltip=i18nc("@info:tooltip","

Sometimes, if source text is changed, its translation becomes deprecated and is either marked as needing review (i.e. looses approval status), " - "or (only in case of XLIFF file) moved to the alternate translations section accompanying the unit.

" - "

This toolview also shows the difference between current source string and the previous source string, so that you can easily see which changes should be applied to existing translation to make it reflect current source.

" - "

Double-clicking any word in this toolview inserts it into translation.

" - "

Drop translation file onto this toolview to use it as a source for additional alternate translations.

" - ); - QToolTip::showText(helpEvent->globalPos(),tooltip); + + if (m_entryPositions.isEmpty()) { + QString tooltip = i18nc("@info:tooltip", "

Sometimes, if source text is changed, its translation becomes deprecated and is either marked as needing review (i.e. looses approval status), " + "or (only in case of XLIFF file) moved to the alternate translations section accompanying the unit.

" + "

This toolview also shows the difference between current source string and the previous source string, so that you can easily see which changes should be applied to existing translation to make it reflect current source.

" + "

Double-clicking any word in this toolview inserts it into translation.

" + "

Drop translation file onto this toolview to use it as a source for additional alternate translations.

" + ); + QToolTip::showText(helpEvent->globalPos(), tooltip); return true; } - int block1=m_browser->cursorForPosition(m_browser->viewport()->mapFromGlobal(helpEvent->globalPos())).blockNumber(); - int block=*m_entryPositions.lowerBound(m_browser->cursorForPosition(m_browser->viewport()->mapFromGlobal(helpEvent->globalPos())).anchor()); - if (block1!=block) - qCWarning(LOKALIZE_LOG)<<"block numbers don't match"; - if (block>=m_entries.size()) + int block1 = m_browser->cursorForPosition(m_browser->viewport()->mapFromGlobal(helpEvent->globalPos())).blockNumber(); + int block = *m_entryPositions.lowerBound(m_browser->cursorForPosition(m_browser->viewport()->mapFromGlobal(helpEvent->globalPos())).anchor()); + if (block1 != block) + qCWarning(LOKALIZE_LOG) << "block numbers don't match"; + if (block >= m_entries.size()) return false; - QString origin=m_entries.at(block).origin; + QString origin = m_entries.at(block).origin; if (origin.isEmpty()) return false; - QString tooltip=i18nc("@info:tooltip","Origin: %1",origin); - QToolTip::showText(helpEvent->globalPos(),tooltip); + QString tooltip = i18nc("@info:tooltip", "Origin: %1", origin); + QToolTip::showText(helpEvent->globalPos(), tooltip); return true; } return QWidget::event(event); } void AltTransView::slotUseSuggestion(int i) { - if (Q_UNLIKELY( i>=m_entries.size() )) + if (Q_UNLIKELY(i >= m_entries.size())) return; TM::TMEntry tmEntry; - tmEntry.target=m_entries.at(i).target; - CatalogString source=m_catalog->sourceWithTags(m_entry.toDocPosition()); - tmEntry.diff=userVisibleWordDiff(m_entries.at(i).source.string, source.string,Project::instance()->accel(),Project::instance()->markup()); + tmEntry.target = m_entries.at(i).target; + CatalogString source = m_catalog->sourceWithTags(m_entry.toDocPosition()); + tmEntry.diff = userVisibleWordDiff(m_entries.at(i).source.string, source.string, Project::instance()->accel(), Project::instance()->markup()); - CatalogString target=TM::targetAdapted(tmEntry, source); + CatalogString target = TM::targetAdapted(tmEntry, source); - qCWarning(LOKALIZE_LOG)<<"0"<beginMacro(i18nc("@item Undo action","Use alternate translation")); + m_catalog->beginMacro(i18nc("@item Undo action", "Use alternate translation")); - QString old=m_catalog->targetWithTags(m_entry.toDocPosition()).string; - if (!old.isEmpty()) - { + QString old = m_catalog->targetWithTags(m_entry.toDocPosition()).string; + if (!old.isEmpty()) { //FIXME test! removeTargetSubstring(m_catalog, m_entry.toDocPosition(), 0, old.size()); //m_catalog->push(new DelTextCmd(m_catalog,m_pos,m_catalog->msgstr(m_pos))); } - qCWarning(LOKALIZE_LOG)<<"1"<push(new InsTextCmd(m_catalog,m_pos,target)/*,true*/); insertCatalogString(m_catalog, m_entry.toDocPosition(), target, 0); diff --git a/src/binunitsview.h b/src/binunitsview.h --- a/src/binunitsview.h +++ b/src/binunitsview.h @@ -39,7 +39,7 @@ class BinUnitsView: public QDockWidget { -Q_OBJECT + Q_OBJECT public: BinUnitsView(Catalog* catalog, QWidget *parent); @@ -61,23 +61,26 @@ class BinUnitsModel: public QAbstractListModel { -Q_OBJECT + Q_OBJECT public: - enum BinUnitsModelColumns - { - SourceFilePath=0, + enum BinUnitsModelColumns { + SourceFilePath = 0, TargetFilePath, Approved, ColumnCount }; BinUnitsModel(Catalog* catalog, QObject* parent); - ~BinUnitsModel(){} + ~BinUnitsModel() {} - int rowCount(const QModelIndex& parent=QModelIndex()) const; - int columnCount(const QModelIndex& parent=QModelIndex()) const{Q_UNUSED(parent); return ColumnCount;} - QVariant data(const QModelIndex&,int role=Qt::DisplayRole) const; - QVariant headerData(int section, Qt::Orientation, int role=Qt::DisplayRole) const; + int rowCount(const QModelIndex& parent = QModelIndex()) const; + int columnCount(const QModelIndex& parent = QModelIndex()) const + { + Q_UNUSED(parent); + return ColumnCount; + } + QVariant data(const QModelIndex&, int role = Qt::DisplayRole) const; + QVariant headerData(int section, Qt::Orientation, int role = Qt::DisplayRole) const; void setTargetFilePath(int row, const QString&); @@ -88,7 +91,7 @@ private: Catalog* m_catalog; - mutable QHash m_imageCache; + mutable QHash m_imageCache; }; diff --git a/src/binunitsview.cpp b/src/binunitsview.cpp --- a/src/binunitsview.cpp +++ b/src/binunitsview.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -58,26 +58,24 @@ void BinUnitsModel::entryModified(const DocPosition& pos) { - if (pos.entrynumberOfEntries()) + if (pos.entry < m_catalog->numberOfEntries()) return; - QModelIndex item=index(pos.entry-m_catalog->numberOfEntries(),TargetFilePath); - emit dataChanged(item,item); + QModelIndex item = index(pos.entry - m_catalog->numberOfEntries(), TargetFilePath); + emit dataChanged(item, item); } void BinUnitsModel::updateFile(QString path) { - QString relPath=QDir(Project::instance()->projectDir()).relativeFilePath(path); + QString relPath = QDir(Project::instance()->projectDir()).relativeFilePath(path); DocPosition pos(m_catalog->numberOfEntries()); - int limit=m_catalog->numberOfEntries()+m_catalog->binUnitsCount(); - while (pos.entrytarget(pos)==relPath || m_catalog->source(pos)==relPath) - { - int row=pos.entry-m_catalog->numberOfEntries(); + int limit = m_catalog->numberOfEntries() + m_catalog->binUnitsCount(); + while (pos.entry < limit) { + if (m_catalog->target(pos) == relPath || m_catalog->source(pos) == relPath) { + int row = pos.entry - m_catalog->numberOfEntries(); m_imageCache.remove(relPath); - emit dataChanged(index(row,SourceFilePath),index(row,TargetFilePath)); + emit dataChanged(index(row, SourceFilePath), index(row, TargetFilePath)); return; } @@ -87,17 +85,16 @@ void BinUnitsModel::setTargetFilePath(int row, const QString& path) { - DocPosition pos(row+m_catalog->numberOfEntries()); - QString old=m_catalog->target(pos); - if (!old.isEmpty()) - { + DocPosition pos(row + m_catalog->numberOfEntries()); + QString old = m_catalog->target(pos); + if (!old.isEmpty()) { m_catalog->push(new DelTextCmd(m_catalog, pos, old)); m_imageCache.remove(old); } m_catalog->push(new InsTextCmd(m_catalog, pos, QDir(Project::instance()->projectDir()).relativeFilePath(path))); - QModelIndex item=index(row,TargetFilePath); - emit dataChanged(item,item); + QModelIndex item = index(row, TargetFilePath); + emit dataChanged(item, item); } int BinUnitsModel::rowCount(const QModelIndex& parent) const @@ -109,61 +106,55 @@ QVariant BinUnitsModel::data(const QModelIndex& index, int role) const { - if (role==Qt::DecorationRole) - { - DocPosition pos(index.row()+m_catalog->numberOfEntries()); - if (index.column()source(pos):m_catalog->target(pos); - if (!m_imageCache.contains(path)) - { - QString absPath=Project::instance()->absolutePath(path); + if (role == Qt::DecorationRole) { + DocPosition pos(index.row() + m_catalog->numberOfEntries()); + if (index.column() < Approved) { + QString path = index.column() == SourceFilePath ? m_catalog->source(pos) : m_catalog->target(pos); + if (!m_imageCache.contains(path)) { + QString absPath = Project::instance()->absolutePath(path); #ifndef NOKDE KDirWatch::self()->addFile(absPath); //TODO remember watched files to react only on them in dirty() signal handler #endif - m_imageCache.insert(path, QImage(absPath).scaled(128,128,Qt::KeepAspectRatio)); + m_imageCache.insert(path, QImage(absPath).scaled(128, 128, Qt::KeepAspectRatio)); } return m_imageCache.value(path); } - } - else if (role==Qt::TextAlignmentRole) - return int(Qt::AlignLeft|Qt::AlignTop); + } else if (role == Qt::TextAlignmentRole) + return int(Qt::AlignLeft | Qt::AlignTop); - if (role!=Qt::DisplayRole) + if (role != Qt::DisplayRole) return QVariant(); - static const char* noyes[]={I18N_NOOP("no"),I18N_NOOP("yes")}; - DocPosition pos(index.row()+m_catalog->numberOfEntries()); - switch (index.column()) - { - case SourceFilePath: return m_catalog->source(pos); - case TargetFilePath: return m_catalog->target(pos); - case Approved: return noyes[m_catalog->isApproved(pos)]; + static const char* noyes[] = {I18N_NOOP("no"), I18N_NOOP("yes")}; + DocPosition pos(index.row() + m_catalog->numberOfEntries()); + switch (index.column()) { + case SourceFilePath: return m_catalog->source(pos); + case TargetFilePath: return m_catalog->target(pos); + case Approved: return noyes[m_catalog->isApproved(pos)]; } return QVariant(); } QVariant BinUnitsModel::headerData(int section, Qt::Orientation, int role) const { - if (role!=Qt::DisplayRole) + if (role != Qt::DisplayRole) return QVariant(); - switch (section) - { - case SourceFilePath: return i18nc("@title:column","Source"); - case TargetFilePath: return i18nc("@title:column","Target"); - case Approved: return i18nc("@title:column","Approved"); + switch (section) { + case SourceFilePath: return i18nc("@title:column", "Source"); + case TargetFilePath: return i18nc("@title:column", "Target"); + case Approved: return i18nc("@title:column", "Approved"); } return QVariant(); } //END BinUnitsModel BinUnitsView::BinUnitsView(Catalog* catalog, QWidget* parent) - : QDockWidget(i18nc("@title toolview name","Binary Units"),parent) - , m_catalog(catalog) - , m_model(new BinUnitsModel(catalog, this)) - , m_view(new MyTreeView(this)) + : QDockWidget(i18nc("@title toolview name", "Binary Units"), parent) + , m_catalog(catalog) + , m_model(new BinUnitsModel(catalog, this)) + , m_view(new MyTreeView(this)) { setObjectName(QStringLiteral("binUnits")); hide(); @@ -185,36 +176,35 @@ void BinUnitsView::selectUnit(const QString& id) { - QModelIndex item=m_model->index(m_catalog->unitById(id)-m_catalog->numberOfEntries()); + QModelIndex item = m_model->index(m_catalog->unitById(id) - m_catalog->numberOfEntries()); m_view->setCurrentIndex(item); m_view->scrollTo(item); show(); } void BinUnitsView::contextMenuEvent(QContextMenuEvent *event) { - QModelIndex item=m_view->currentIndex(); + QModelIndex item = m_view->currentIndex(); if (!item.isValid()) return; QMenu menu; - QAction* setTarget=menu.addAction(i18nc("@action:inmenu","Set the file")); - QAction* useSource=menu.addAction(i18nc("@action:inmenu","Use source file")); + QAction* setTarget = menu.addAction(i18nc("@action:inmenu", "Set the file")); + QAction* useSource = menu.addAction(i18nc("@action:inmenu", "Use source file")); // menu.addSeparator(); // QAction* openSource=menu.addAction(i18nc("@action:inmenu","Open source file in external program")); // QAction* openTarget=menu.addAction(i18nc("@action:inmenu","Open target file in external program")); - QAction* result=menu.exec(event->globalPos()); + QAction* result = menu.exec(event->globalPos()); if (!result) return; - QString sourceFilePath=item.sibling(item.row(),BinUnitsModel::SourceFilePath).data().toString(); - if (result==useSource) + QString sourceFilePath = item.sibling(item.row(), BinUnitsModel::SourceFilePath).data().toString(); + if (result == useSource) m_model->setTargetFilePath(item.row(), sourceFilePath); - else if (result==setTarget) - { - QString targetFilePath=QFileDialog::getOpenFileName(this, QString(), Project::instance()->projectDir()); + else if (result == setTarget) { + QString targetFilePath = QFileDialog::getOpenFileName(this, QString(), Project::instance()->projectDir()); if (!targetFilePath.isEmpty()) m_model->setTargetFilePath(item.row(), targetFilePath); } @@ -225,7 +215,7 @@ { #ifndef NOKDE //FIXME child processes don't notify us about changes ;( - if (item.column()absolutePath(item.data().toString())), this); #endif } diff --git a/src/catalog/alttrans.h b/src/catalog/alttrans.h --- a/src/catalog/alttrans.h +++ b/src/catalog/alttrans.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -27,8 +27,7 @@ #include "catalogstring.h" #include "tmentry.h" -struct AltTrans -{ +struct AltTrans { ///@see @link http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#alttranstype enum Type {Proposal, PreviousVersion, Rejected, Reference, Accepted, Other}; Type type; @@ -42,7 +41,7 @@ QString origin; QString phase; - AltTrans(const CatalogString& s=CatalogString(), const QString& o=QString()):type(Other),source(s),score(0),origin(o){} + AltTrans(const CatalogString& s = CatalogString(), const QString& o = QString()): type(Other), source(s), score(0), origin(o) {} }; diff --git a/src/catalog/catalog.h b/src/catalog/catalog.h --- a/src/catalog/catalog.h +++ b/src/catalog/catalog.h @@ -30,7 +30,7 @@ your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. - + **************************************************************************** */ #ifndef CATALOG_H @@ -50,17 +50,18 @@ #include -namespace GettextCatalog { - class CatalogImportPlugin; - class CatalogExportPlugin; +namespace GettextCatalog +{ +class CatalogImportPlugin; +class CatalogExportPlugin; } bool isApproved(TargetState state, ProjectLocal::PersonRole role); bool isApproved(TargetState state); //disregarding Phase TargetState closestState(bool approved, ProjectLocal::PersonRole role); -int findPrevInList(const QLinkedList& list,int index); -int findNextInList(const QLinkedList& list,int index); +int findPrevInList(const QLinkedList& list, int index); +int findNextInList(const QLinkedList& list, int index); void insertInList(QLinkedList& list, int index); // insert index in the right place in the list @@ -93,8 +94,14 @@ void push(QUndoCommand* cmd); public slots: //DBus interface - QString source(const DocPosition& pos) const {return msgid(pos);} - QString target(const DocPosition& pos) const {return msgstr(pos);} + QString source(const DocPosition& pos) const + { + return msgid(pos); + } + QString target(const DocPosition& pos) const + { + return msgstr(pos); + } // used by XLIFF storage) CatalogString sourceWithTags(const DocPosition& pos) const; CatalogString targetWithTags(const DocPosition& pos) const; @@ -117,20 +124,32 @@ ///@returns previous phase-name QString setPhase(const DocPosition& pos, const QString& phase); QString phase(const DocPosition& pos) const; - QString activePhase() const{return d._phase;} - ProjectLocal::PersonRole activePhaseRole() const{return d._phaseRole;} - void setActivePhase(const QString& phase, ProjectLocal::PersonRole role=ProjectLocal::Approver); + QString activePhase() const + { + return d._phase; + } + ProjectLocal::PersonRole activePhaseRole() const + { + return d._phaseRole; + } + void setActivePhase(const QString& phase, ProjectLocal::PersonRole role = ProjectLocal::Approver); Phase phase(const QString& name) const; QList allPhases() const; - QMap allTools() const; + QMap allTools() const; QVector phaseNotes(const QString& phase) const; ///@arg pos.entry - number of phase, @arg pos.form - number of note QVector setPhaseNotes(const QString& phase, QVector); bool isPlural(uint index) const; - bool isPlural(const DocPosition& pos) const{return isPlural(pos.entry);} + bool isPlural(const DocPosition& pos) const + { + return isPlural(pos.entry); + } bool isApproved(uint index) const; - bool isApproved(const DocPosition& pos) const{return isApproved(pos.entry);} + bool isApproved(const DocPosition& pos) const + { + return isApproved(pos.entry); + } TargetState state(const DocPosition& pos) const; bool isEquivTrans(const DocPosition&) const; ///@returns true if at least one form is untranslated @@ -145,37 +164,94 @@ int unitById(const QString& id) const; - bool isBookmarked(uint index) const{return d._bookmarkIndex.contains(index);} + bool isBookmarked(uint index) const + { + return d._bookmarkIndex.contains(index); + } void setBookmark(uint, bool); - int numberOfPluralForms() const {return d._numberOfPluralForms;} + int numberOfPluralForms() const + { + return d._numberOfPluralForms; + } int numberOfEntries() const; - int numberOfNonApproved() const {return d._nonApprovedIndex.size();} - int numberOfUntranslated() const {return d._emptyIndex.size();} + int numberOfNonApproved() const + { + return d._nonApprovedIndex.size(); + } + int numberOfUntranslated() const + { + return d._emptyIndex.size(); + } public: QString originalOdfFilePath(); void setOriginalOdfFilePath(const QString&); - int firstFuzzyIndex() const {return d._nonApprovedIndex.isEmpty()?numberOfEntries():d._nonApprovedIndex.first();} - int lastFuzzyIndex() const {return d._nonApprovedIndex.isEmpty()?-1:d._nonApprovedIndex.last();} - int nextFuzzyIndex(uint index) const {return findNextInList(d._nonApprovedIndex,index);} - int prevFuzzyIndex(uint index) const {return findPrevInList(d._nonApprovedIndex,index);} - int firstUntranslatedIndex() const {return d._emptyIndex.isEmpty()?numberOfEntries():d._emptyIndex.first();} - int lastUntranslatedIndex() const {return d._emptyIndex.isEmpty()?-1:d._emptyIndex.last();} - int nextUntranslatedIndex(uint index) const {return findNextInList(d._emptyIndex,index);} - int prevUntranslatedIndex(uint index) const {return findPrevInList(d._emptyIndex,index);} - - int firstBookmarkIndex() const {return d._bookmarkIndex.isEmpty()?numberOfEntries():d._bookmarkIndex.first();} - int lastBookmarkIndex() const {return d._bookmarkIndex.isEmpty()?-1:d._bookmarkIndex.last();} - int nextBookmarkIndex(uint index) const {return findNextInList(d._bookmarkIndex,index);} - int prevBookmarkIndex(uint index) const {return findPrevInList(d._bookmarkIndex,index);} - - bool autoSaveRecovered(){return d._autoSaveRecovered;} + int firstFuzzyIndex() const + { + return d._nonApprovedIndex.isEmpty() ? numberOfEntries() : d._nonApprovedIndex.first(); + } + int lastFuzzyIndex() const + { + return d._nonApprovedIndex.isEmpty() ? -1 : d._nonApprovedIndex.last(); + } + int nextFuzzyIndex(uint index) const + { + return findNextInList(d._nonApprovedIndex, index); + } + int prevFuzzyIndex(uint index) const + { + return findPrevInList(d._nonApprovedIndex, index); + } + int firstUntranslatedIndex() const + { + return d._emptyIndex.isEmpty() ? numberOfEntries() : d._emptyIndex.first(); + } + int lastUntranslatedIndex() const + { + return d._emptyIndex.isEmpty() ? -1 : d._emptyIndex.last(); + } + int nextUntranslatedIndex(uint index) const + { + return findNextInList(d._emptyIndex, index); + } + int prevUntranslatedIndex(uint index) const + { + return findPrevInList(d._emptyIndex, index); + } + + int firstBookmarkIndex() const + { + return d._bookmarkIndex.isEmpty() ? numberOfEntries() : d._bookmarkIndex.first(); + } + int lastBookmarkIndex() const + { + return d._bookmarkIndex.isEmpty() ? -1 : d._bookmarkIndex.last(); + } + int nextBookmarkIndex(uint index) const + { + return findNextInList(d._bookmarkIndex, index); + } + int prevBookmarkIndex(uint index) const + { + return findPrevInList(d._bookmarkIndex, index); + } + + bool autoSaveRecovered() + { + return d._autoSaveRecovered; + } public: void clear(); - bool isEmpty(){return !m_storage;} - bool isReadOnly(){return d._readOnly;} + bool isEmpty() + { + return !m_storage; + } + bool isReadOnly() + { + return d._readOnly; + } void attachAltTransCatalog(Catalog*); void attachAltTrans(int entry, const AltTrans& trans); @@ -187,11 +263,17 @@ void setTarget(DocPosition pos, const CatalogString& s); //for batch use only! //void setErrorIndex(const QList& errors){d._errorIndex=errors;} - void setUrl(const QString& u){d._filePath=u;}//used for template load + void setUrl(const QString& u) + { + d._filePath = u; //used for template load + } public slots: //DBus interface - const QString& url() const {return d._filePath;} + const QString& url() const + { + return d._filePath; + } ///@returns 0 if success, >0 erroneous line (parsing error) - int loadFromUrl(const QString& url, const QString& saidUrl=QString(), int* fileSize = 0, bool fast = false); + int loadFromUrl(const QString& url, const QString& saidUrl = QString(), int* fileSize = 0, bool fast = false); bool saveToUrl(QString url); bool save(); QByteArray contents(); @@ -211,8 +293,11 @@ protected slots: void doAutoSave(); - void setAutoSaveDirty(){d._autoSaveDirty=true;} - + void setAutoSaveDirty() + { + d._autoSaveDirty = true; + } + void projectConfigChanged(); protected: @@ -240,7 +325,7 @@ /// @returns true if entry wasn't modified before bool setModified(DocPos entry, bool modif); - + void updateApprovedEmptyIndexCache(); protected: @@ -263,7 +348,7 @@ public: //static QString supportedMimeFilters; - static QString supportedFileTypes(bool includeTemplates=true); + static QString supportedFileTypes(bool includeTemplates = true); signals: void signalEntryModified(const DocPosition&); diff --git a/src/catalog/catalog.cpp b/src/catalog/catalog.cpp --- a/src/catalog/catalog.cpp +++ b/src/catalog/catalog.cpp @@ -74,17 +74,18 @@ //QString Catalog::supportedMimeFilters("text/x-gettext-translation application/x-xliff application/x-linguist"); //" text/x-gettext-translation-template") QString Catalog::supportedFileTypes(bool includeTemplates) { - QString sep=QStringLiteral(";;"); - QString all=i18n("All supported files (*.po *.pot *.xlf *.xliff *.ts)")+sep; - return all+(includeTemplates ? i18n("Gettext (*.po *.pot)") : i18n("Gettext (*.po)"))+sep+i18n("XLIFF (*.xlf *.xliff)")+sep+i18n("Linguist (*.ts)"); + QString sep = QStringLiteral(";;"); + QString all = i18n("All supported files (*.po *.pot *.xlf *.xliff *.ts)") + sep; + return all + (includeTemplates ? i18n("Gettext (*.po *.pot)") : i18n("Gettext (*.po)")) + sep + i18n("XLIFF (*.xlf *.xliff)") + sep + i18n("Linguist (*.ts)"); } -static const QString extensions[]={U(".po"),U(".pot"),U(".xlf"),U(".xliff"),U(".ts")}; +static const QString extensions[] = {U(".po"), U(".pot"), U(".xlf"), U(".xliff"), U(".ts")}; -static const char* const xliff_states[]={ - I18N_NOOP("New"),I18N_NOOP("Needs translation"),I18N_NOOP("Needs full localization"),I18N_NOOP("Needs adaptation"),I18N_NOOP("Translated"), - I18N_NOOP("Needs translation review"),I18N_NOOP("Needs full localization review"),I18N_NOOP("Needs adaptation review"),I18N_NOOP("Final"), - I18N_NOOP("Signed-off")}; +static const char* const xliff_states[] = { + I18N_NOOP("New"), I18N_NOOP("Needs translation"), I18N_NOOP("Needs full localization"), I18N_NOOP("Needs adaptation"), I18N_NOOP("Translated"), + I18N_NOOP("Needs translation review"), I18N_NOOP("Needs full localization review"), I18N_NOOP("Needs adaptation review"), I18N_NOOP("Final"), + I18N_NOOP("Signed-off") +}; const char* const* Catalog::states() { @@ -94,19 +95,19 @@ QStringList Catalog::supportedExtensions() { QStringList result; - int i=sizeof(extensions)/sizeof(QString); - while (--i>=0) + int i = sizeof(extensions) / sizeof(QString); + while (--i >= 0) result.append(extensions[i]); return result; } bool Catalog::extIsSupported(const QString& path) { - QStringList ext=supportedExtensions(); - int i=ext.size(); - while (--i>=0 && !path.endsWith(ext.at(i))) + QStringList ext = supportedExtensions(); + int i = ext.size(); + while (--i >= 0 && !path.endsWith(ext.at(i))) ; - return i!=-1; + return i != -1; } Catalog::Catalog(QObject *parent) @@ -116,10 +117,10 @@ { #ifndef NOKDE //cause refresh events for files modified from lokalize itself aint delivered automatically - connect(this, QOverload::of(&Catalog::signalFileSaved), Project::instance()->model(), QOverload::of(&ProjectModel::slotFileSaved),Qt::QueuedConnection); + connect(this, QOverload::of(&Catalog::signalFileSaved), Project::instance()->model(), QOverload::of(&ProjectModel::slotFileSaved), Qt::QueuedConnection); - QTimer* t=&(d._autoSaveTimer); - t->setInterval(2*60*1000); + QTimer* t = &(d._autoSaveTimer); + t->setInterval(2 * 60 * 1000); t->setSingleShot(false); connect(t, &QTimer::timeout, this, &Catalog::doAutoSave); connect(this, QOverload<>::of(&Catalog::signalFileSaved), t, QOverload<>::of(&QTimer::start)); @@ -143,20 +144,20 @@ d._errorIndex.clear(); d._nonApprovedIndex.clear(); d._emptyIndex.clear(); - delete m_storage;m_storage=0; + delete m_storage; m_storage = 0; d._filePath.clear(); - d._lastModifiedPos=DocPosition(); + d._lastModifiedPos = DocPosition(); d._modifiedEntries.clear(); while (!d._altTransCatalogs.isEmpty()) d._altTransCatalogs.takeFirst()->deleteLater(); - + d._altTranslations.clear(); -/* - d.msgidDiffList.clear(); - d.msgstr2MsgidDiffList.clear(); - d.diffCache.clear(); - */ + /* + d.msgidDiffList.clear(); + d.msgstr2MsgidDiffList.clear(); + d.diffCache.clear(); + */ } @@ -172,105 +173,105 @@ int Catalog::capabilities() const { - if (Q_UNLIKELY( !m_storage )) return 0; + if (Q_UNLIKELY(!m_storage)) return 0; return m_storage->capabilities(); } int Catalog::numberOfEntries() const { - if (Q_UNLIKELY( !m_storage )) return 0; + if (Q_UNLIKELY(!m_storage)) return 0; return m_storage->size(); } static DocPosition alterForSinglePlural(const Catalog* th, DocPosition pos) { //if source lang is english (implied) and target lang has only 1 plural form (e.g. Chinese) - if (Q_UNLIKELY(th->numberOfPluralForms()==1 && th->isPlural(pos))) - pos.form=1; + if (Q_UNLIKELY(th->numberOfPluralForms() == 1 && th->isPlural(pos))) + pos.form = 1; return pos; } QString Catalog::msgid(const DocPosition& pos) const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return QString(); return m_storage->source(alterForSinglePlural(this, pos)); } QString Catalog::msgstr(const DocPosition& pos) const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return QString(); - return m_storage->target(pos); + return m_storage->target(pos); } CatalogString Catalog::sourceWithTags(const DocPosition& pos) const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return CatalogString(); return m_storage->sourceWithTags(alterForSinglePlural(this, pos)); } CatalogString Catalog::targetWithTags(const DocPosition& pos) const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return CatalogString(); return m_storage->targetWithTags(pos); } CatalogString Catalog::catalogString(const DocPosition& pos) const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return CatalogString(); - return m_storage->catalogString(pos.part==DocPosition::Source?alterForSinglePlural(this, pos):pos); + return m_storage->catalogString(pos.part == DocPosition::Source ? alterForSinglePlural(this, pos) : pos); } QVector Catalog::notes(const DocPosition& pos) const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return QVector(); return m_storage->notes(pos); } QVector Catalog::developerNotes(const DocPosition& pos) const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return QVector(); return m_storage->developerNotes(pos); } Note Catalog::setNote(const DocPosition& pos, const Note& note) { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return Note(); - return m_storage->setNote(pos,note); + return m_storage->setNote(pos, note); } QStringList Catalog::noteAuthors() const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return QStringList(); return m_storage->noteAuthors(); } void Catalog::attachAltTransCatalog(Catalog* altCat) { d._altTransCatalogs.append(altCat); - if (numberOfEntries()!=altCat->numberOfEntries()) - qCWarning(LOKALIZE_LOG)<url()<<"has different number of entries"; + if (numberOfEntries() != altCat->numberOfEntries()) + qCWarning(LOKALIZE_LOG) << altCat->url() << "has different number of entries"; } void Catalog::attachAltTrans(int entry, const AltTrans& trans) @@ -282,106 +283,101 @@ { QVector result; if (m_storage) - result=m_storage->altTrans(pos); + result = m_storage->altTrans(pos); - foreach(Catalog* altCat, d._altTransCatalogs) - { - if (pos.entry>=altCat->numberOfEntries()) - { - qCDebug(LOKALIZE_LOG)<<"ignoring"<url()<<"this time because"<numberOfEntries(); + foreach (Catalog* altCat, d._altTransCatalogs) { + if (pos.entry >= altCat->numberOfEntries()) { + qCDebug(LOKALIZE_LOG) << "ignoring" << altCat->url() << "this time because" << pos.entry << "<" << altCat->numberOfEntries(); continue; } - if (altCat->source(pos)!=source(pos)) - { - qCDebug(LOKALIZE_LOG)<<"ignoring"<url()<<"this time because s don't match"; + if (altCat->source(pos) != source(pos)) { + qCDebug(LOKALIZE_LOG) << "ignoring" << altCat->url() << "this time because s don't match"; continue; } - QString target=altCat->msgstr(pos); - if (!target.isEmpty() && altCat->isApproved(pos)) - { - result<url(); + QString target = altCat->msgstr(pos); + if (!target.isEmpty() && altCat->isApproved(pos)) { + result << AltTrans(); + result.last().target = target; + result.last().type = AltTrans::Reference; + result.last().origin = altCat->url(); } } if (d._altTranslations.contains(pos.entry)) - result<sourceFiles(pos); } QString Catalog::id(const DocPosition& pos) const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return QString(); return m_storage->id(pos); } QStringList Catalog::context(const DocPosition& pos) const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return QStringList(); return m_storage->context(pos); } QString Catalog::setPhase(const DocPosition& pos, const QString& phase) { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return QString(); - return m_storage->setPhase(pos,phase); + return m_storage->setPhase(pos, phase); } void Catalog::setActivePhase(const QString& phase, ProjectLocal::PersonRole role) { //qCDebug(LOKALIZE_LOG)<<"setting active phase"<size(); - while (pos.entrysize(); + while (pos.entry < limit) { if (!isApproved(pos)) d._nonApprovedIndex << pos.entry; if (m_storage->isEmpty(pos)) d._emptyIndex << pos.entry; ++(pos.entry); } - + emit signalNumberOfFuzziesChanged(); emit signalNumberOfEmptyChanged(); } QString Catalog::phase(const DocPosition& pos) const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return QString(); return m_storage->phase(pos); @@ -407,7 +403,7 @@ return m_storage->setPhaseNotes(phase, notes); } -QMap Catalog::allTools() const +QMap Catalog::allTools() const { return m_storage->allTools(); } @@ -419,18 +415,18 @@ bool Catalog::isApproved(uint index) const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return false; - bool extendedStates=m_storage->capabilities()&ExtendedStates; + bool extendedStates = m_storage->capabilities()&ExtendedStates; - return (extendedStates&&::isApproved(state(DocPosition(index)),activePhaseRole())) - ||(!extendedStates&&m_storage->isApproved(DocPosition(index))); + return (extendedStates &&::isApproved(state(DocPosition(index)), activePhaseRole())) + || (!extendedStates && m_storage->isApproved(DocPosition(index))); } TargetState Catalog::state(const DocPosition& pos) const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return NeedsTranslation; if (m_storage->capabilities()&ExtendedStates) @@ -457,60 +453,60 @@ int Catalog::binUnitsCount() const { - return m_storage?m_storage->binUnitsCount():0; + return m_storage ? m_storage->binUnitsCount() : 0; } int Catalog::unitById(const QString& id) const { - return m_storage?m_storage->unitById(id):0; + return m_storage ? m_storage->unitById(id) : 0; } QString Catalog::mimetype() { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return QString(); return m_storage->mimetype(); } QString Catalog::fileType() { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return QString(); return m_storage->fileType(); } CatalogType Catalog::type() { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return Gettext; return m_storage->type(); } QString Catalog::sourceLangCode() const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return QString(); return m_storage->sourceLangCode(); } QString Catalog::targetLangCode() const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return QString(); return m_storage->targetLangCode(); } void Catalog::setTargetLangCode(const QString& targetLangCode) { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return; - bool notify = m_storage->targetLangCode()!=targetLangCode; + bool notify = m_storage->targetLangCode() != targetLangCode; m_storage->setTargetLangCode(targetLangCode); if (notify) emit signalFileLoaded(); } @@ -525,20 +521,17 @@ KAutoSaveFile* Catalog::checkAutoSave(const QString& url) { #ifndef NOKDE - KAutoSaveFile* autoSave=0; + KAutoSaveFile* autoSave = 0; QList staleFiles = KAutoSaveFile::staleFiles(QUrl::fromLocalFile(url)); - foreach (KAutoSaveFile *stale, staleFiles) - { - if (stale->open(QIODevice::ReadOnly) && !autoSave) - { - autoSave=stale; + foreach (KAutoSaveFile *stale, staleFiles) { + if (stale->open(QIODevice::ReadOnly) && !autoSave) { + autoSave = stale; autoSave->setParent(this); - } - else + } else stale->deleteLater(); } if (autoSave) - qCInfo(LOKALIZE_LOG)<<"autoSave"<fileName(); + qCInfo(LOKALIZE_LOG) << "autoSave" << autoSave->fileName(); return autoSave; #else return 0; @@ -548,91 +541,86 @@ int Catalog::loadFromUrl(const QString& filePath, const QString& saidUrl, int* fileSize, bool fast) { QFileInfo info(filePath); - if(Q_UNLIKELY( !info.exists() || info.isDir()) ) + if (Q_UNLIKELY(!info.exists() || info.isDir())) return DOESNTEXIST; - if(Q_UNLIKELY( !info.isReadable() )) + if (Q_UNLIKELY(!info.isReadable())) return ISNTREADABLE; - bool readOnly=!info.isWritable(); + bool readOnly = !info.isWritable(); - QTime a;a.start(); + QTime a; a.start(); QFile file(filePath); if (!file.open(QIODevice::ReadOnly)) return ISNTREADABLE;//TODO - CatalogStorage* storage=0; - if (filePath.endsWith(QLatin1String(".po"))||filePath.endsWith(QLatin1String(".pot"))) - storage=new GettextCatalog::GettextStorage; - else if (filePath.endsWith(QLatin1String(".xlf"))||filePath.endsWith(QLatin1String(".xliff"))) - storage=new XliffStorage; + CatalogStorage* storage = 0; + if (filePath.endsWith(QLatin1String(".po")) || filePath.endsWith(QLatin1String(".pot"))) + storage = new GettextCatalog::GettextStorage; + else if (filePath.endsWith(QLatin1String(".xlf")) || filePath.endsWith(QLatin1String(".xliff"))) + storage = new XliffStorage; else if (filePath.endsWith(QLatin1String(".ts"))) - storage=new TsStorage; - else - { + storage = new TsStorage; + else { //try harder QTextStream in(&file); - int i=0; - bool gettext=false; - while (!in.atEnd()&& ++i<64 && !gettext) - gettext=in.readLine().contains(QLatin1String("msgid")); - if (gettext) storage=new GettextCatalog::GettextStorage; + int i = 0; + bool gettext = false; + while (!in.atEnd() && ++i < 64 && !gettext) + gettext = in.readLine().contains(QLatin1String("msgid")); + if (gettext) storage = new GettextCatalog::GettextStorage; else return UNKNOWNFORMAT; } - int line=storage->load(&file); + int line = storage->load(&file); file.close(); - if (Q_UNLIKELY(line!=0 || (!storage->size() && (line==-1) ) )) - { + if (Q_UNLIKELY(line != 0 || (!storage->size() && (line == -1)))) { delete storage; return line; } - if (a.elapsed()>100) qCDebug(LOKALIZE_LOG)< 100) qCDebug(LOKALIZE_LOG) << filePath << "opened in" << a.elapsed(); //ok... clear(); //commit transaction - m_storage=storage; + m_storage = storage; updateApprovedEmptyIndexCache(); - + d._numberOfPluralForms = storage->numberOfPluralForms(); - d._autoSaveDirty=true; - d._readOnly=readOnly; - d._filePath=saidUrl.isEmpty()?filePath:saidUrl; + d._autoSaveDirty = true; + d._readOnly = readOnly; + d._filePath = saidUrl.isEmpty() ? filePath : saidUrl; //set some sane role, a real phase with a nmae will be created later with the first edit command - setActivePhase(QString(),Project::local()->role()); + setActivePhase(QString(), Project::local()->role()); #ifndef NOKDE - if (!fast) - { - KAutoSaveFile* autoSave=checkAutoSave(d._filePath); - d._autoSaveRecovered=autoSave; - if (autoSave) - { + if (!fast) { + KAutoSaveFile* autoSave = checkAutoSave(d._filePath); + d._autoSaveRecovered = autoSave; + if (autoSave) { d._autoSave->deleteLater(); - d._autoSave=autoSave; + d._autoSave = autoSave; //restore 'modified' status for entries - MergeCatalog* mergeCatalog=new MergeCatalog(this,this); - int errorLine=mergeCatalog->loadFromUrl(autoSave->fileName()); - if (Q_LIKELY(errorLine==0)) + MergeCatalog* mergeCatalog = new MergeCatalog(this, this); + int errorLine = mergeCatalog->loadFromUrl(autoSave->fileName()); + if (Q_LIKELY(errorLine == 0)) mergeCatalog->copyToBaseCatalog(); mergeCatalog->deleteLater(); d._autoSave->close(); - } - else + } else d._autoSave->setManagedFile(QUrl::fromLocalFile(d._filePath)); } #endif if (fileSize) - *fileSize=file.size(); + *fileSize = file.size(); emit signalFileLoaded(); emit signalFileLoaded(d._filePath); @@ -647,35 +635,34 @@ //this function is not called if QUndoStack::isClean() ! bool Catalog::saveToUrl(QString localFilePath) { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return true; - bool nameChanged=localFilePath.length(); - if (Q_LIKELY( !nameChanged )) + bool nameChanged = localFilePath.length(); + if (Q_LIKELY(!nameChanged)) localFilePath = d._filePath; - QString localPath=QFileInfo(localFilePath).absolutePath(); + QString localPath = QFileInfo(localFilePath).absolutePath(); if (!QFileInfo::exists(localPath)) if (!QDir::root().mkpath(localPath)) return false; QFile file(localFilePath); - if (Q_UNLIKELY( !file.open(QIODevice::WriteOnly) )) //i18n("Wasn't able to open file %1",filename.ascii()); + if (Q_UNLIKELY(!file.open(QIODevice::WriteOnly))) //i18n("Wasn't able to open file %1",filename.ascii()); return false; - bool belongsToProject=localFilePath.contains(Project::instance()->poDir()); - if (Q_UNLIKELY( !m_storage->save(&file, belongsToProject) )) + bool belongsToProject = localFilePath.contains(Project::instance()->poDir()); + if (Q_UNLIKELY(!m_storage->save(&file, belongsToProject))) return false; file.close(); #ifndef NOKDE d._autoSave->remove(); - d._autoSaveRecovered=false; + d._autoSaveRecovered = false; #endif setClean(); //undo/redo - if (nameChanged) - { - d._filePath=localFilePath; + if (nameChanged) { + d._filePath = localFilePath; #ifndef NOKDE d._autoSave->setManagedFile(QUrl::fromLocalFile(localFilePath)); #endif @@ -687,35 +674,34 @@ emit signalFileSaved(); emit signalFileSaved(localFilePath); return true; -/* - else if (status==NO_PERMISSIONS) - { - if (KMessageBox::warningContinueCancel(this, - i18n("You do not have permission to write to file:\n%1\n" - "Do you want to save to another file or cancel?", _currentURL.prettyUrl()), - i18n("Error"),KStandardGuiItem::save())==KMessageBox::Continue) - return fileSaveAs(); + /* + else if (status==NO_PERMISSIONS) + { + if (KMessageBox::warningContinueCancel(this, + i18n("You do not have permission to write to file:\n%1\n" + "Do you want to save to another file or cancel?", _currentURL.prettyUrl()), + i18n("Error"),KStandardGuiItem::save())==KMessageBox::Continue) + return fileSaveAs(); - } -*/ + } + */ } void Catalog::doAutoSave() { #ifndef NOKDE - if (isClean()||!(d._autoSaveDirty)) + if (isClean() || !(d._autoSaveDirty)) return; - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return; - if (!d._autoSave->open(QIODevice::WriteOnly)) - { + if (!d._autoSave->open(QIODevice::WriteOnly)) { emit signalFileAutoSaveFailed(d._autoSave->fileName()); return; } - qCInfo(LOKALIZE_LOG)<<"doAutoSave"<fileName(); + qCInfo(LOKALIZE_LOG) << "doAutoSave" << d._autoSave->fileName(); m_storage->save(d._autoSave); d._autoSave->close(); - d._autoSaveDirty=false; + d._autoSaveDirty = false; #endif } @@ -737,25 +723,25 @@ - /** - * helper method to keep db in a good shape :) - * called on - * 1) entry switch - * 2) automatic editing code like replace or undo/redo operation - **/ +/** + * helper method to keep db in a good shape :) + * called on + * 1) entry switch + * 2) automatic editing code like replace or undo/redo operation +**/ static void updateDB( - const QString& filePath, - const QString& ctxt, - const CatalogString& english, - const CatalogString& newTarget, - int form, - bool approved, - const QString& dbName - //const DocPosition&,//for back tracking - ) -{ - TM::UpdateJob* j=new TM::UpdateJob(filePath,ctxt,english,newTarget,form,approved, - dbName); + const QString& filePath, + const QString& ctxt, + const CatalogString& english, + const CatalogString& newTarget, + int form, + bool approved, + const QString& dbName + //const DocPosition&,//for back tracking +) +{ + TM::UpdateJob* j = new TM::UpdateJob(filePath, ctxt, english, newTarget, form, approved, + dbName); TM::threadPool()->start(j); } @@ -778,128 +764,121 @@ if (!Settings::autoaddTM()) return; - DocPosition pos=d._lastModifiedPos; - if (pos.entry==-1 || pos.entry>=numberOfEntries()) - { + DocPosition pos = d._lastModifiedPos; + if (pos.entry == -1 || pos.entry >= numberOfEntries()) { //nothing to flush //qCWarning(LOKALIZE_LOG)<<"nothing to flush or new file opened"; return; } QString dbName; - if (Project::instance()->targetLangCode()==targetLangCode()) - { - dbName=Project::instance()->projectID(); - } - else - { - dbName=sourceLangCode()%'-'%targetLangCode(); - qCInfo(LOKALIZE_LOG)<<"updating"<targetLangCode()<m_configurations.contains(dbName)) - { - TM::OpenDBJob* openDBJob=new TM::OpenDBJob(dbName, TM::Local, true); + if (Project::instance()->targetLangCode() == targetLangCode()) { + dbName = Project::instance()->projectID(); + } else { + dbName = sourceLangCode() % '-' % targetLangCode(); + qCInfo(LOKALIZE_LOG) << "updating" << dbName << "because target language of project db does not match" << Project::instance()->targetLangCode() << targetLangCode(); + if (!TM::DBFilesModel::instance()->m_configurations.contains(dbName)) { + TM::OpenDBJob* openDBJob = new TM::OpenDBJob(dbName, TM::Local, true); connect(openDBJob, &TM::OpenDBJob::done, TM::DBFilesModel::instance(), &TM::DBFilesModel::updateProjectTmIndex); - openDBJob->m_setParams=true; - openDBJob->m_tmConfig.markup=Project::instance()->markup(); - openDBJob->m_tmConfig.accel=Project::instance()->accel(); - openDBJob->m_tmConfig.sourceLangCode=sourceLangCode(); - openDBJob->m_tmConfig.targetLangCode=targetLangCode(); + openDBJob->m_setParams = true; + openDBJob->m_tmConfig.markup = Project::instance()->markup(); + openDBJob->m_tmConfig.accel = Project::instance()->accel(); + openDBJob->m_tmConfig.sourceLangCode = sourceLangCode(); + openDBJob->m_tmConfig.targetLangCode = targetLangCode(); TM::DBFilesModel::instance()->openDB(openDBJob); } } - int form=-1; + int form = -1; if (isPlural(pos.entry)) - form=pos.form; + form = pos.form; updateDB(url(), context(pos.entry).first(), sourceWithTags(pos), targetWithTags(pos), form, isApproved(pos.entry), dbName); - d._lastModifiedPos=DocPosition(); + d._lastModifiedPos = DocPosition(); } void Catalog::setLastModifiedPos(const DocPosition& pos) { - if (pos.entry>=numberOfEntries()) //bin-units + if (pos.entry >= numberOfEntries()) //bin-units return; - bool entryChanged=DocPos(d._lastModifiedPos)!=DocPos(pos); + bool entryChanged = DocPos(d._lastModifiedPos) != DocPos(pos); if (entryChanged) flushUpdateDBBuffer(); - d._lastModifiedPos=pos; + d._lastModifiedPos = pos; } bool CatalogPrivate::addToEmptyIndexIfAppropriate(CatalogStorage* storage, const DocPosition& pos, bool alreadyEmpty) { - if ((!pos.offset)&&(storage->target(pos).isEmpty())&&(!alreadyEmpty)) - { - insertInList(_emptyIndex,pos.entry); + if ((!pos.offset) && (storage->target(pos).isEmpty()) && (!alreadyEmpty)) { + insertInList(_emptyIndex, pos.entry); return true; } return false; } void Catalog::targetDelete(const DocPosition& pos, int count) { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return; bool alreadyEmpty = m_storage->isEmpty(pos); - m_storage->targetDelete(pos,count); + m_storage->targetDelete(pos, count); - if (d.addToEmptyIndexIfAppropriate(m_storage,pos,alreadyEmpty)) + if (d.addToEmptyIndexIfAppropriate(m_storage, pos, alreadyEmpty)) emit signalNumberOfEmptyChanged(); emit signalEntryModified(pos); } bool CatalogPrivate::removeFromUntransIndexIfAppropriate(CatalogStorage* storage, const DocPosition& pos) { - if ((!pos.offset)&&(storage->isEmpty(pos))) - { + if ((!pos.offset) && (storage->isEmpty(pos))) { _emptyIndex.removeAll(pos.entry); return true; } return false; } void Catalog::targetInsert(const DocPosition& pos, const QString& arg) { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return; - if (d.removeFromUntransIndexIfAppropriate(m_storage,pos)) + if (d.removeFromUntransIndexIfAppropriate(m_storage, pos)) emit signalNumberOfEmptyChanged(); - m_storage->targetInsert(pos,arg); + m_storage->targetInsert(pos, arg); emit signalEntryModified(pos); } void Catalog::targetInsertTag(const DocPosition& pos, const InlineTag& tag) { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return; - if (d.removeFromUntransIndexIfAppropriate(m_storage,pos)) + if (d.removeFromUntransIndexIfAppropriate(m_storage, pos)) emit signalNumberOfEmptyChanged(); - m_storage->targetInsertTag(pos,tag); + m_storage->targetInsertTag(pos, tag); emit signalEntryModified(pos); } InlineTag Catalog::targetDeleteTag(const DocPosition& pos) { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return InlineTag(); bool alreadyEmpty = m_storage->isEmpty(pos); - InlineTag tag=m_storage->targetDeleteTag(pos); + InlineTag tag = m_storage->targetDeleteTag(pos); - if (d.addToEmptyIndexIfAppropriate(m_storage,pos,alreadyEmpty)) + if (d.addToEmptyIndexIfAppropriate(m_storage, pos, alreadyEmpty)) emit signalNumberOfEmptyChanged(); emit signalEntryModified(pos); return tag; @@ -914,27 +893,24 @@ TargetState Catalog::setState(const DocPosition& pos, TargetState state) { bool extendedStates = m_storage && m_storage->capabilities()&ExtendedStates; - bool approved=::isApproved(state,activePhaseRole()); - if (Q_UNLIKELY( !m_storage - || (extendedStates && m_storage->state(pos)==state) - || (!extendedStates && m_storage->isApproved(pos)==approved))) + bool approved =::isApproved(state, activePhaseRole()); + if (Q_UNLIKELY(!m_storage + || (extendedStates && m_storage->state(pos) == state) + || (!extendedStates && m_storage->isApproved(pos) == approved))) return this->state(pos); TargetState prevState; - if (extendedStates) - { - prevState=m_storage->setState(pos,state); + if (extendedStates) { + prevState = m_storage->setState(pos, state); d._statesIndex[prevState].removeAll(pos.entry); - insertInList(d._statesIndex[state],pos.entry); - } - else - { - prevState=closestState(!approved,activePhaseRole()); - m_storage->setApproved(pos,approved); + insertInList(d._statesIndex[state], pos.entry); + } else { + prevState = closestState(!approved, activePhaseRole()); + m_storage->setApproved(pos, approved); } if (!approved) - insertInList(d._nonApprovedIndex,pos.entry); + insertInList(d._nonApprovedIndex, pos.entry); else d._nonApprovedIndex.removeAll(pos.entry); @@ -956,13 +932,11 @@ bool Catalog::setModified(DocPos entry, bool modified) { - if (modified) - { + if (modified) { if (d._modifiedEntries.contains(entry)) return false; d._modifiedEntries.insert(entry); - } - else + } else d._modifiedEntries.remove(entry); return true; } @@ -975,11 +949,11 @@ bool Catalog::isModified(int entry) const { if (!isPlural(entry)) - return isModified(DocPos(entry,0)); + return isModified(DocPos(entry, 0)); - int f=numberOfPluralForms(); - while(--f>=0) - if (isModified(DocPos(entry,f))) + int f = numberOfPluralForms(); + while (--f >= 0) + if (isModified(DocPos(entry, f))) return true; return false; } @@ -991,11 +965,9 @@ int findNextInList(const QLinkedList& list, int index) { - int nextIndex=-1; - foreach(int key, list) - { - if (Q_UNLIKELY( key>index )) - { + int nextIndex = -1; + foreach (int key, list) { + if (Q_UNLIKELY(key > index)) { nextIndex = key; break; } @@ -1005,49 +977,48 @@ int findPrevInList(const QLinkedList& list, int index) { - int prevIndex=-1; - foreach(int key, list) - { - if (Q_UNLIKELY( key>=index )) + int prevIndex = -1; + foreach (int key, list) { + if (Q_UNLIKELY(key >= index)) break; prevIndex = key; } return prevIndex; } void insertInList(QLinkedList& list, int index) { - QLinkedList::Iterator it=list.begin(); - while(it != list.end() && index > *it) + QLinkedList::Iterator it = list.begin(); + while (it != list.end() && index > *it) ++it; - list.insert(it,index); + list.insert(it, index); } void Catalog::setBookmark(uint idx, bool set) { if (set) - insertInList(d._bookmarkIndex,idx); + insertInList(d._bookmarkIndex, idx); else d._bookmarkIndex.removeAll(idx); } bool isApproved(TargetState state, ProjectLocal::PersonRole role) { - static const TargetState marginStates[]={Translated, Final, SignedOff}; - return state>=marginStates[role]; + static const TargetState marginStates[] = {Translated, Final, SignedOff}; + return state >= marginStates[role]; } bool isApproved(TargetState state) { - static const TargetState marginStates[]={Translated, Final, SignedOff}; - return state==marginStates[0] || state==marginStates[1] || state==marginStates[2]; + static const TargetState marginStates[] = {Translated, Final, SignedOff}; + return state == marginStates[0] || state == marginStates[1] || state == marginStates[2]; } TargetState closestState(bool approved, ProjectLocal::PersonRole role) { - Q_ASSERT(role!=ProjectLocal::Undefined); - static const TargetState approvementStates[][3]={ + Q_ASSERT(role != ProjectLocal::Undefined); + static const TargetState approvementStates[][3] = { {NeedsTranslation, NeedsReviewTranslation, NeedsReviewTranslation}, {Translated, Final, SignedOff} }; @@ -1057,23 +1028,23 @@ bool Catalog::isObsolete(int entry) const { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return false; return m_storage->isObsolete(entry); } QString Catalog::originalOdfFilePath() { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return QString(); return m_storage->originalOdfFilePath(); } void Catalog::setOriginalOdfFilePath(const QString& odfFilePath) { - if (Q_UNLIKELY( !m_storage )) + if (Q_UNLIKELY(!m_storage)) return; m_storage->setOriginalOdfFilePath(odfFilePath); diff --git a/src/catalog/catalog_private.h b/src/catalog/catalog_private.h --- a/src/catalog/catalog_private.h +++ b/src/catalog/catalog_private.h @@ -3,8 +3,8 @@ This file is based on the one from KBabel Copyright (C) 1999-2000 by Matthias Kiefer - 2001-2004 by Stanislav Visnovsky - 2007 by Nick Shaforostoff + 2001-2004 by Stanislav Visnovsky + 2007 by Nick Shaforostoff This program is free software; you can redistribute it and/or modify @@ -108,16 +108,16 @@ ProjectLocal::PersonRole _phaseRole; explicit CatalogPrivate(QObject* parent) - : fileCodec(0) - , _numberOfPluralForms(-1) + : fileCodec(0) + , _numberOfPluralForms(-1) #ifndef NOKDE - , _autoSave(new KAutoSaveFile(parent)) + , _autoSave(new KAutoSaveFile(parent)) #endif - , _autoSaveDirty(true) - , _autoSaveRecovered(false) - , _readOnly(false) - , _maxLineLength(80) - , _phaseRole(ProjectLocal::Undefined) + , _autoSaveDirty(true) + , _autoSaveRecovered(false) + , _readOnly(false) + , _maxLineLength(80) + , _phaseRole(ProjectLocal::Undefined) { Q_UNUSED(parent) _statesIndex.resize(StateCount); diff --git a/src/catalog/catalogcapabilities.h b/src/catalog/catalogcapabilities.h --- a/src/catalog/catalogcapabilities.h +++ b/src/catalog/catalogcapabilities.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -24,17 +24,15 @@ #ifndef CATALOGCAPABILITIES_H #define CATALOGCAPABILITIES_H -enum CatalogCapabilities -{ - KeepsNoteAuthors=1, - MultipleNotes=2, - Phases=4, - ExtendedStates=8, - Tags=16 +enum CatalogCapabilities { + KeepsNoteAuthors = 1, + MultipleNotes = 2, + Phases = 4, + ExtendedStates = 8, + Tags = 16 }; -enum CatalogType -{ +enum CatalogType { Gettext, Xliff, Ts diff --git a/src/catalog/catalogstorage.h b/src/catalog/catalogstorage.h --- a/src/catalog/catalogstorage.h +++ b/src/catalog/catalogstorage.h @@ -41,62 +41,106 @@ * @short Abstract interface for storage of translation file * @author Nick Shaforostoff */ -class CatalogStorage { +class CatalogStorage +{ public: CatalogStorage(); virtual ~CatalogStorage(); - virtual int capabilities() const=0; + virtual int capabilities() const = 0; - virtual int load(QIODevice* device)=0; - virtual bool save(QIODevice* device, bool belongsToProject=false)=0; + virtual int load(QIODevice* device) = 0; + virtual bool save(QIODevice* device, bool belongsToProject = false) = 0; - virtual int size() const=0; - int numberOfEntries()const{return size();} - int numberOfPluralForms() const{return m_numberOfPluralForms;} + virtual int size() const = 0; + int numberOfEntries()const + { + return size(); + } + int numberOfPluralForms() const + { + return m_numberOfPluralForms; + } /** * flat-model interface (ignores XLIFF grouping) * * format-specific texts like \" for gettext PO should be eliminated **/ - virtual QString source(const DocPosition& pos) const=0; - virtual QString target(const DocPosition& pos) const=0; - virtual CatalogString sourceWithTags(DocPosition pos) const=0; - virtual CatalogString targetWithTags(DocPosition pos) const=0; - virtual CatalogString catalogString(const DocPosition& pos) const=0; + virtual QString source(const DocPosition& pos) const = 0; + virtual QString target(const DocPosition& pos) const = 0; + virtual CatalogString sourceWithTags(DocPosition pos) const = 0; + virtual CatalogString targetWithTags(DocPosition pos) const = 0; + virtual CatalogString catalogString(const DocPosition& pos) const = 0; /** * edit operations used by undo/redo system and sync-mode **/ - virtual void targetDelete(const DocPosition& pos, int count)=0; - virtual void targetInsert(const DocPosition& pos, const QString& arg)=0; - virtual void setTarget(const DocPosition& pos, const QString& arg)=0;//called for mergeCatalog TODO switch to CatalogString - virtual void targetInsertTag(const DocPosition&, const InlineTag&){} - virtual InlineTag targetDeleteTag(const DocPosition&){return InlineTag();} - virtual Phase updatePhase(const Phase&){return Phase();} - virtual QList allPhases() const{return QList();} - virtual QMap allTools() const{return QMap();} + virtual void targetDelete(const DocPosition& pos, int count) = 0; + virtual void targetInsert(const DocPosition& pos, const QString& arg) = 0; + virtual void setTarget(const DocPosition& pos, const QString& arg) = 0; //called for mergeCatalog TODO switch to CatalogString + virtual void targetInsertTag(const DocPosition&, const InlineTag&) {} + virtual InlineTag targetDeleteTag(const DocPosition&) + { + return InlineTag(); + } + virtual Phase updatePhase(const Phase&) + { + return Phase(); + } + virtual QList allPhases() const + { + return QList(); + } + virtual QMap allTools() const + { + return QMap(); + } /// all plural forms. pos.form doesn't matter - virtual QStringList sourceAllForms(const DocPosition& pos, bool stripNewLines=false) const=0; - virtual QStringList targetAllForms(const DocPosition& pos, bool stripNewLines=false) const=0; - - virtual QVector altTrans(const DocPosition& pos) const=0; - virtual QVector notes(const DocPosition& pos) const=0; - virtual Note setNote(DocPosition pos, const Note& note)=0; - virtual QStringList noteAuthors() const{return QStringList();} - virtual QVector developerNotes(const DocPosition& pos) const=0; - virtual QStringList sourceFiles(const DocPosition& pos) const=0; - - virtual QString setPhase(const DocPosition& pos, const QString& phase){Q_UNUSED(pos); Q_UNUSED(phase); return QString();} - virtual QString phase(const DocPosition& pos) const {Q_UNUSED(pos); return QString();} - virtual Phase phase(const QString& name) const{Q_UNUSED(name); return Phase();} - virtual QVector phaseNotes(const QString& phase) const{Q_UNUSED(phase); return QVector();} - virtual QVector setPhaseNotes(const QString& phase, QVector notes){Q_UNUSED(phase); Q_UNUSED(notes); return QVector();} + virtual QStringList sourceAllForms(const DocPosition& pos, bool stripNewLines = false) const = 0; + virtual QStringList targetAllForms(const DocPosition& pos, bool stripNewLines = false) const = 0; + + virtual QVector altTrans(const DocPosition& pos) const = 0; + virtual QVector notes(const DocPosition& pos) const = 0; + virtual Note setNote(DocPosition pos, const Note& note) = 0; + virtual QStringList noteAuthors() const + { + return QStringList(); + } + virtual QVector developerNotes(const DocPosition& pos) const = 0; + virtual QStringList sourceFiles(const DocPosition& pos) const = 0; + + virtual QString setPhase(const DocPosition& pos, const QString& phase) + { + Q_UNUSED(pos); + Q_UNUSED(phase); + return QString(); + } + virtual QString phase(const DocPosition& pos) const + { + Q_UNUSED(pos); + return QString(); + } + virtual Phase phase(const QString& name) const + { + Q_UNUSED(name); + return Phase(); + } + virtual QVector phaseNotes(const QString& phase) const + { + Q_UNUSED(phase); + return QVector(); + } + virtual QVector setPhaseNotes(const QString& phase, QVector notes) + { + Q_UNUSED(phase); + Q_UNUSED(notes); + return QVector(); + } //the result must be guaranteed to have at least 1 string - virtual QStringList context(const DocPosition&) const=0; + virtual QStringList context(const DocPosition&) const = 0; //DocPosition.form - number of //virtual QString context(const DocPosition&) const=0; //virtual int contextCount(const DocPosition&) const=0; @@ -113,46 +157,95 @@ * * pos.form doesn't matter **/ - virtual QStringList matchData(const DocPosition&) const=0; + virtual QStringList matchData(const DocPosition&) const = 0; /** * entry id unique for this file * * pos.form doesn't matter **/ - virtual QString id(const DocPosition&) const=0; - - virtual bool isPlural(const DocPosition&) const=0; - - virtual bool isEmpty(const DocPosition&) const=0; - - virtual bool isEquivTrans(const DocPosition&) const{return true;} - virtual void setEquivTrans(const DocPosition&, bool equivTrans){Q_UNUSED(equivTrans)} - - virtual bool isApproved(const DocPosition&) const{return true;} - virtual void setApproved(const DocPosition&, bool approved){Q_UNUSED(approved)} - virtual TargetState state(const DocPosition&) const{return New;} - virtual TargetState setState(const DocPosition&, TargetState){return New;} - - virtual bool isObsolete(int entry) const{ Q_UNUSED(entry) return false;} - virtual bool isTranslateable(int entry) const{ Q_UNUSED(entry) return true;} - - virtual int binUnitsCount() const {return 0;} - virtual int unitById(const QString& id) const {Q_UNUSED(id); return 0;} - - const QString& url() const {return m_url;} - void setUrl(const QString& u){m_url=u;}//TODO - - virtual QString mimetype() const=0; - virtual QString fileType() const=0; - virtual CatalogType type() const=0; - - virtual QString originalOdfFilePath(){return QString();} - virtual void setOriginalOdfFilePath(const QString&){} - - QString sourceLangCode() const{return m_sourceLangCode;} - QString targetLangCode() const{return m_targetLangCode;} - virtual void setTargetLangCode(const QString& langCode) {m_targetLangCode=langCode;} + virtual QString id(const DocPosition&) const = 0; + + virtual bool isPlural(const DocPosition&) const = 0; + + virtual bool isEmpty(const DocPosition&) const = 0; + + virtual bool isEquivTrans(const DocPosition&) const + { + return true; + } + virtual void setEquivTrans(const DocPosition&, bool equivTrans) + { + Q_UNUSED(equivTrans) + } + + virtual bool isApproved(const DocPosition&) const + { + return true; + } + virtual void setApproved(const DocPosition&, bool approved) + { + Q_UNUSED(approved) + } + virtual TargetState state(const DocPosition&) const + { + return New; + } + virtual TargetState setState(const DocPosition&, TargetState) + { + return New; + } + + virtual bool isObsolete(int entry) const + { + Q_UNUSED(entry) return false; + } + virtual bool isTranslateable(int entry) const + { + Q_UNUSED(entry) return true; + } + + virtual int binUnitsCount() const + { + return 0; + } + virtual int unitById(const QString& id) const + { + Q_UNUSED(id); + return 0; + } + + const QString& url() const + { + return m_url; + } + void setUrl(const QString& u) + { + m_url = u; //TODO + } + + virtual QString mimetype() const = 0; + virtual QString fileType() const = 0; + virtual CatalogType type() const = 0; + + virtual QString originalOdfFilePath() + { + return QString(); + } + virtual void setOriginalOdfFilePath(const QString&) {} + + QString sourceLangCode() const + { + return m_sourceLangCode; + } + QString targetLangCode() const + { + return m_targetLangCode; + } + virtual void setTargetLangCode(const QString& langCode) + { + m_targetLangCode = langCode; + } protected: QString m_url; diff --git a/src/catalog/catalogstring.h b/src/catalog/catalogstring.h --- a/src/catalog/catalogstring.h +++ b/src/catalog/catalogstring.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -37,17 +37,15 @@ * a XLIFF tag is represented by a TAGRANGE_IMAGE_SYMBOL in the 'plainttext' * and a struct TagRange * - * describes which tag is behind TAGRANGE_IMAGE_SYMBOL char + * describes which tag is behind TAGRANGE_IMAGE_SYMBOL char * (or chars -- starting and ending) in source or target string * start==end for non-paired tags */ -struct InlineTag -{ +struct InlineTag { //sub = can contain -flow tag //recursive = can contain other inline markup tags ///@see http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html - enum InlineElement - { + enum InlineElement { _unknown, bpt, //sub ept, //sub @@ -73,10 +71,10 @@ QString equivText; QString ctype; - explicit InlineTag(): start(-1), end(-1), type(_unknown){} + explicit InlineTag(): start(-1), end(-1), type(_unknown) {} - InlineTag(int start_, int end_, InlineElement type_,QString id_=QString(),QString xid_=QString(),QString equivText_=QString(),QString ctype_=QString()) - : start(start_), end(end_), type(type_), id(id_), xid(xid_), equivText(equivText_), ctype(ctype_){} + InlineTag(int start_, int end_, InlineElement type_, QString id_ = QString(), QString xid_ = QString(), QString equivText_ = QString(), QString ctype_ = QString()) + : start(start_), end(end_), type(type_), id(id_), xid(xid_), equivText(equivText_), ctype(ctype_) {} /** * for situations when target doesn't contain tag @@ -86,7 +84,10 @@ * * @see getPlaceholder() */ - bool isEmpty()const{return start==-1;} + bool isEmpty()const + { + return start == -1; + } /** * used to denote tag that doesn't present in target, @@ -100,16 +101,28 @@ ///@returns 0 if type is unknown static InlineElement getElementType(const QByteArray&); static const char* getElementName(InlineElement type); - const char* getElementName()const{return getElementName(type);} - const char* name()const{return getElementName();} - static bool isPaired(InlineElement type){return type tags; - CatalogString(){} - CatalogString(QString str):string(str){} + CatalogString() {} + CatalogString(QString str): string(str) {} CatalogString(QString str, QByteArray tagsByteArray); - QMap tagIdToIndex() const; //assigns same indexes for tags with same ids + QMap tagIdToIndex() const; //assigns same indexes for tags with same ids QByteArray tagsAsByteArray()const; void remove(int position, int len); void insert(int position, const QString& str); - void replace(int position, int len, const QString& str){remove(position,len);insert(position,str);} - void clear(){string.clear();tags.clear();} - bool isEmpty() const {return string.isEmpty();} + void replace(int position, int len, const QString& str) + { + remove(position, len); + insert(position, str); + } + void clear() + { + string.clear(); + tags.clear(); + } + bool isEmpty() const + { + return string.isEmpty(); + } }; Q_DECLARE_METATYPE(CatalogString) diff --git a/src/catalog/catalogstring.cpp b/src/catalog/catalogstring.cpp --- a/src/catalog/catalogstring.cpp +++ b/src/catalog/catalogstring.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -30,46 +30,46 @@ const char* InlineTag::getElementName(InlineElement type) { - static const char* inlineElementNames[(int)InlineElementCount]={ - "_unknown", - "bpt", - "ept", - "ph", - "it", - //"_NEVERSHOULDBECHOSEN", - "mrk", - "g", - "sub", - "_NEVERSHOULDBECHOSEN", - "x", - "bx", - "ex" + static const char* inlineElementNames[(int)InlineElementCount] = { + "_unknown", + "bpt", + "ept", + "ph", + "it", + //"_NEVERSHOULDBECHOSEN", + "mrk", + "g", + "sub", + "_NEVERSHOULDBECHOSEN", + "x", + "bx", + "ex" }; return inlineElementNames[(int)type]; } InlineTag InlineTag::getPlaceholder() const { - InlineTag tagRange=*this; - tagRange.start=-1; - tagRange.end=-1; + InlineTag tagRange = *this; + tagRange.start = -1; + tagRange.end = -1; return tagRange; } InlineTag::InlineElement InlineTag::getElementType(const QByteArray& tag) { - int i=InlineTag::InlineElementCount; - while(--i>0) - if (getElementName(InlineElement(i))==tag) + int i = InlineTag::InlineElementCount; + while (--i > 0) + if (getElementName(InlineElement(i)) == tag) break; return InlineElement(i); } QString InlineTag::displayName() const { - static const char* inlineElementNames[(int)InlineElementCount]={ + static const char* inlineElementNames[(int)InlineElementCount] = { "_unknown", I18N_NOOP2("XLIFF inline tag name", "Start of paired tag"), I18N_NOOP2("XLIFF inline tag name", "End of paired tag"), @@ -85,11 +85,10 @@ I18N_NOOP2("XLIFF inline tag name", "End of paired placeholder") }; - QString result=i18nc("XLIFF inline tag name", inlineElementNames[type]); + QString result = i18nc("XLIFF inline tag name", inlineElementNames[type]); - if (type==mrk) - { - static const char* mrkTypes[]={ + if (type == mrk) { + static const char* mrkTypes[] = { "abbrev", "abbreviated-form", "abbreviation", @@ -129,7 +128,7 @@ "variant" }; - static const char* mrkTypeNames[]={ + static const char* mrkTypeNames[] = { I18N_NOOP2("XLIFF mark type", "abbreviation"), I18N_NOOP2("XLIFF mark type", "abbreviated form: a term resulting from the omission of any part of the full term while designating the same concept"), I18N_NOOP2("XLIFF mark type", "abbreviation: an abbreviated form of a simple term resulting from the omission of some of its letters (e.g. 'adj.' for 'adjective')"), @@ -168,31 +167,29 @@ I18N_NOOP2("XLIFF mark type", "truncated term: an abbreviated form of a term resulting from the omission of one or more term elements or syllables (e.g. 'flu' for 'influenza')"), I18N_NOOP2("XLIFF mark type", "variant: one of the alternate forms of a term") }; - int i=sizeof(mrkTypes)/sizeof(char*); - while(--i>=0 && mrkTypes[i]!=id) + int i = sizeof(mrkTypes) / sizeof(char*); + while (--i >= 0 && mrkTypes[i] != id) ; - if (i!=-1) - { - result=i18nc("XLIFF mark type", mrkTypeNames[i]); + if (i != -1) { + result = i18nc("XLIFF mark type", mrkTypeNames[i]); if (!result.isEmpty()) - result[0]=result.at(0).toUpper(); + result[0] = result.at(0).toUpper(); } } - + if (!ctype.isEmpty()) - result+=" ("+ctype+")"; + result += " (" + ctype + ")"; return result; } -QMap CatalogString::tagIdToIndex() const +QMap CatalogString::tagIdToIndex() const { - QMap result; - int index=0; - int count=tags.size(); - for (int i=0;i result; + int index = 0; + int count = tags.size(); + for (int i = 0; i < count; ++i) { if (!result.contains(tags.at(i).id)) result.insert(tags.at(i).id, index++); } @@ -202,136 +199,127 @@ QByteArray CatalogString::tagsAsByteArray()const { QByteArray result; - if (tags.size()) - { - QDataStream stream(&result,QIODevice::WriteOnly); - stream<>tags; + stream >> tags; } } static void adjustTags(QList& tags, int position, int value) { - int i=tags.size(); - while(--i>=0) - { - InlineTag& t=tags[i]; - if (t.start>position) - t.start+=value; - if (t.end>=position) //cases when strict > is needed? - t.end+=value; + int i = tags.size(); + while (--i >= 0) { + InlineTag& t = tags[i]; + if (t.start > position) + t.start += value; + if (t.end >= position) //cases when strict > is needed? + t.end += value; } } void CatalogString::remove(int position, int len) { - string.remove(position,len); - adjustTags(tags,position,-len); + string.remove(position, len); + adjustTags(tags, position, -len); } void CatalogString::insert(int position, const QString& str) { string.insert(position, str); - adjustTags(tags,position,str.size()); + adjustTags(tags, position, str.size()); } QDataStream &operator<<(QDataStream &out, const InlineTag &t) { - return out<>(QDataStream &in, InlineTag &t) { int type; - in>>type>>t.start>>t.end>>t.id; - t.type=InlineTag::InlineElement(type); + in >> type >> t.start >> t.end >> t.id; + t.type = InlineTag::InlineElement(type); return in; } QDataStream &operator<<(QDataStream &out, const CatalogString &myObj) { - return out<>(QDataStream &in, CatalogString &myObj) { - return in>>myObj.string>>myObj.tags; + return in >> myObj.string >> myObj.tags; } void adaptCatalogString(CatalogString& target, const CatalogString& ref) { - qCWarning(LOKALIZE_LOG)<<"HERE"< id2tagIndex; - QMultiMap tagType2tagIndex; - int i=ref.tags.size(); - while(--i>=0) - { - const InlineTag& t=ref.tags.at(i); - id2tagIndex.insert(t.id,i); - tagType2tagIndex.insert(t.type,i); - qCWarning(LOKALIZE_LOG)<<"inserting"< id2tagIndex; + QMultiMap tagType2tagIndex; + int i = ref.tags.size(); + while (--i >= 0) { + const InlineTag& t = ref.tags.at(i); + id2tagIndex.insert(t.id, i); + tagType2tagIndex.insert(t.type, i); + qCWarning(LOKALIZE_LOG) << "inserting" << t.id << t.type << i; } - QList oldTags=target.tags; + QList oldTags = target.tags; target.tags.clear(); //we actually walking from beginning to end: qSort(oldTags.begin(), oldTags.end(), qGreater()); - i=oldTags.size(); - while(--i>=0) - { - const InlineTag& targetTag=oldTags.at(i); - if (id2tagIndex.contains(targetTag.id)) - { - qCWarning(LOKALIZE_LOG)<<"matched"<= 0) { + const InlineTag& targetTag = oldTags.at(i); + if (id2tagIndex.contains(targetTag.id)) { + qCWarning(LOKALIZE_LOG) << "matched" << targetTag.id << i; target.tags.append(targetTag); tagType2tagIndex.remove(targetTag.type, id2tagIndex.take(targetTag.id)); oldTags.removeAt(i); } } - qCWarning(LOKALIZE_LOG)<<"HERE 0"<=0) - { - InlineTag targetTag=oldTags.at(i); - if (tagType2tagIndex.contains(targetTag.type)) - { + i = oldTags.size(); + while (--i >= 0) { + InlineTag targetTag = oldTags.at(i); + if (tagType2tagIndex.contains(targetTag.type)) { //try to match by position //we're _taking_ first so the next one becomes new 'first' for the next time. QList possibleRefMatches; - foreach(int i, tagType2tagIndex.values(targetTag.type)) - possibleRefMatches<& tagPlaces, const CatalogString& catalogString, int start, int len); -bool removeTargetSubstring(Catalog* catalog, DocPosition pos, int delStart=0, int delLen=-1); -void insertCatalogString(Catalog* catalog, DocPosition pos, const CatalogString& catStr, int start=0); +bool fillTagPlaces(QMap& tagPlaces, const CatalogString& catalogString, int start, int len); +bool removeTargetSubstring(Catalog* catalog, DocPosition pos, int delStart = 0, int delLen = -1); +void insertCatalogString(Catalog* catalog, DocPosition pos, const CatalogString& catStr, int start = 0); #endif // CMD_H diff --git a/src/catalog/cmd.cpp b/src/catalog/cmd.cpp --- a/src/catalog/cmd.cpp +++ b/src/catalog/cmd.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -36,33 +36,33 @@ //BEGIN LokalizeUnitCmd -LokalizeUnitCmd::LokalizeUnitCmd(Catalog *catalog, const DocPosition& pos, const QString& name=QString()) +LokalizeUnitCmd::LokalizeUnitCmd(Catalog *catalog, const DocPosition& pos, const QString& name = QString()) : QUndoCommand(name) , _catalog(catalog) , _pos(pos) , _firstModificationForThisEntry(false) {} static QString setPhaseForPart(Catalog* catalog, const QString& phase, DocPosition phasePos, DocPosition::Part part) { - phasePos.part=part; - return catalog->setPhase(phasePos,phase); + phasePos.part = part; + return catalog->setPhase(phasePos, phase); } void LokalizeUnitCmd::redo() { setJumpingPos(); doRedo(); - _firstModificationForThisEntry=_catalog->setModified(DocPos(_pos),true); + _firstModificationForThisEntry = _catalog->setModified(DocPos(_pos), true); // _prevPhase=setPhaseForPart(_catalog,_catalog->activePhase(),_pos,DocPosition::UndefPart); } void LokalizeUnitCmd::undo() { setJumpingPos(); doUndo(); if (_firstModificationForThisEntry) - _catalog->setModified(DocPos(_pos),false); + _catalog->setModified(DocPos(_pos), false); // setPhaseForPart(_catalog,_prevPhase,_pos,DocPosition::UndefPart); } @@ -73,154 +73,152 @@ //END LokalizeUnitCmd //BEGIN LokalizeTargetCmd -LokalizeTargetCmd::LokalizeTargetCmd(Catalog *catalog, const DocPosition& pos, const QString& name=QString()) - : LokalizeUnitCmd(catalog,pos,name) +LokalizeTargetCmd::LokalizeTargetCmd(Catalog *catalog, const DocPosition& pos, const QString& name = QString()) + : LokalizeUnitCmd(catalog, pos, name) {} void LokalizeTargetCmd::redo() { LokalizeUnitCmd::redo(); - _prevTargetPhase=setPhaseForPart(_catalog,_catalog->activePhase(),_pos,DocPosition::Target); + _prevTargetPhase = setPhaseForPart(_catalog, _catalog->activePhase(), _pos, DocPosition::Target); } void LokalizeTargetCmd::undo() { LokalizeUnitCmd::undo(); - setPhaseForPart(_catalog,_prevTargetPhase,_pos,DocPosition::Target); + setPhaseForPart(_catalog, _prevTargetPhase, _pos, DocPosition::Target); } //END LokalizeTargetCmd //BEGIN InsTextCmd InsTextCmd::InsTextCmd(Catalog *catalog, const DocPosition& pos, const QString& str) - : LokalizeTargetCmd(catalog,pos,i18nc("@item Undo action item","Insertion")) + : LokalizeTargetCmd(catalog, pos, i18nc("@item Undo action item", "Insertion")) , _str(str) {} bool InsTextCmd::mergeWith(const QUndoCommand *other) { - const DocPosition otherPos=static_cast(other)->pos(); + const DocPosition otherPos = static_cast(other)->pos(); if ((other->id() != id()) - || (otherPos.entry!=_pos.entry) - || (otherPos.form!=_pos.form) - || (otherPos.offset!=_pos.offset+_str.size()) - ) + || (otherPos.entry != _pos.entry) + || (otherPos.form != _pos.form) + || (otherPos.offset != _pos.offset + _str.size()) + ) return false; const QString& otherStr = static_cast(other)->_str; if (otherStr.isEmpty() || _str.isEmpty()) //just a precaution return false; //be close to behaviour of LibreOffice - if (!_str.at(_str.size()-1).isSpace() && otherStr.at(0).isSpace()) + if (!_str.at(_str.size() - 1).isSpace() && otherStr.at(0).isSpace()) return false; _str += otherStr; return true; } void InsTextCmd::doRedo() { - Catalog& catalog=*_catalog; - DocPosition pos=_pos; pos.offset+=_str.size(); + Catalog& catalog = *_catalog; + DocPosition pos = _pos; pos.offset += _str.size(); catalog.setLastModifiedPos(pos); - catalog.targetInsert(_pos,_str); + catalog.targetInsert(_pos, _str); } void InsTextCmd::doUndo() { - _catalog->targetDelete(_pos,_str.size()); + _catalog->targetDelete(_pos, _str.size()); } //END InsTextCmd //BEGIN DelTextCmd -DelTextCmd::DelTextCmd(Catalog *catalog,const DocPosition &pos,const QString &str) - : LokalizeTargetCmd(catalog,pos,i18nc("@item Undo action item","Deletion")) +DelTextCmd::DelTextCmd(Catalog *catalog, const DocPosition &pos, const QString &str) + : LokalizeTargetCmd(catalog, pos, i18nc("@item Undo action item", "Deletion")) , _str(str) {} bool DelTextCmd::mergeWith(const QUndoCommand *other) { - const DocPosition otherPos=static_cast(other)->pos(); + const DocPosition otherPos = static_cast(other)->pos(); if ( (other->id() != id()) - || (otherPos.entry!=_pos.entry) - || (otherPos.form!=_pos.form) - ) + || (otherPos.entry != _pos.entry) + || (otherPos.form != _pos.form) + ) return false; //Delete - if (otherPos.offset==_pos.offset) - { + if (otherPos.offset == _pos.offset) { _str += static_cast(other)->_str; return true; } //BackSpace - if (otherPos.offset==_pos.offset-static_cast(other)->_str.size()) - { + if (otherPos.offset == _pos.offset - static_cast(other)->_str.size()) { _str.prepend(static_cast(other)->_str); - _pos.offset=otherPos.offset; + _pos.offset = otherPos.offset; return true; } return false; } void DelTextCmd::doRedo() { - _catalog->targetDelete(_pos,_str.size()); + _catalog->targetDelete(_pos, _str.size()); } void DelTextCmd::doUndo() { //DocPosition pos=_pos; //pos.offset+=_str.size(); //_catalog.setLastModifiedPos(pos); - _catalog->targetInsert(_pos,_str); + _catalog->targetInsert(_pos, _str); } //END DelTextCmd //BEGIN SetStateCmd void SetStateCmd::push(Catalog *catalog, const DocPosition& pos, bool approved) { - catalog->push(new SetStateCmd(catalog,pos,closestState(approved,catalog->activePhaseRole()))); + catalog->push(new SetStateCmd(catalog, pos, closestState(approved, catalog->activePhaseRole()))); } void SetStateCmd::instantiateAndPush(Catalog *catalog, const DocPosition& pos, TargetState state) { - catalog->push(new SetStateCmd(catalog,pos,state)); + catalog->push(new SetStateCmd(catalog, pos, state)); } SetStateCmd::SetStateCmd(Catalog *catalog, const DocPosition& pos, TargetState state) - : LokalizeUnitCmd(catalog,pos,i18nc("@item Undo action item","Approvement toggling")) + : LokalizeUnitCmd(catalog, pos, i18nc("@item Undo action item", "Approvement toggling")) , _state(state) , _prevState(SignedOff) //shut up static analyzer {} void SetStateCmd::doRedo() { - _prevState=_catalog->setState(_pos,_state); + _prevState = _catalog->setState(_pos, _state); } void SetStateCmd::doUndo() { - _catalog->setState(_pos,_prevState); + _catalog->setState(_pos, _prevState); } //END SetStateCmd //BEGIN InsTagCmd InsTagCmd::InsTagCmd(Catalog *catalog, const DocPosition& pos, const InlineTag& tag) - : LokalizeTargetCmd(catalog,pos,i18nc("@item Undo action item","Markup Insertion")) + : LokalizeTargetCmd(catalog, pos, i18nc("@item Undo action item", "Markup Insertion")) , _tag(tag) { - _pos.offset=tag.start; + _pos.offset = tag.start; } void InsTagCmd::doRedo() { - Catalog& catalog=*_catalog; - DocPosition pos=_pos; pos.offset++; //between paired tags or after single tag + Catalog& catalog = *_catalog; + DocPosition pos = _pos; pos.offset++; //between paired tags or after single tag catalog.setLastModifiedPos(pos); - catalog.targetInsertTag(_pos,_tag); + catalog.targetInsertTag(_pos, _tag); } void InsTagCmd::doUndo() @@ -231,71 +229,71 @@ //BEGIN DelTagCmd DelTagCmd::DelTagCmd(Catalog *catalog, const DocPosition& pos) - : LokalizeTargetCmd(catalog,pos,i18nc("@item Undo action item","Markup Deletion")) + : LokalizeTargetCmd(catalog, pos, i18nc("@item Undo action item", "Markup Deletion")) {} void DelTagCmd::doRedo() { - _tag=_catalog->targetDeleteTag(_pos); - qCDebug(LOKALIZE_LOG)<<"tag properties:"<<_tag.start<<_tag.end; + _tag = _catalog->targetDeleteTag(_pos); + qCDebug(LOKALIZE_LOG) << "tag properties:" << _tag.start << _tag.end; } void DelTagCmd::doUndo() { - Catalog& catalog=*_catalog; - DocPosition pos=_pos; pos.offset++; //between paired tags or after single tag + Catalog& catalog = *_catalog; + DocPosition pos = _pos; pos.offset++; //between paired tags or after single tag catalog.setLastModifiedPos(pos); - catalog.targetInsertTag(_pos,_tag); + catalog.targetInsertTag(_pos, _tag); } //END DelTagCmd //BEGIN SetNoteCmd SetNoteCmd::SetNoteCmd(Catalog *catalog, const DocPosition& pos, const Note& note) - : LokalizeUnitCmd(catalog,pos,i18nc("@item Undo action item","Note setting")) + : LokalizeUnitCmd(catalog, pos, i18nc("@item Undo action item", "Note setting")) , _note(note) { - _pos.part=DocPosition::Comment; + _pos.part = DocPosition::Comment; } static void setNote(Catalog& catalog, DocPosition& _pos, const Note& note, Note& resultNote) { - resultNote=catalog.setNote(_pos,note); - int size=catalog.notes(_pos).size(); - if (_pos.form>=size) _pos.form = -1; + resultNote = catalog.setNote(_pos, note); + int size = catalog.notes(_pos).size(); + if (_pos.form >= size) _pos.form = -1; #if 0 - else if (_pos.form==-1) _pos.form = size-1; + else if (_pos.form == -1) _pos.form = size - 1; #endif } void SetNoteCmd::doRedo() { - setNote(*_catalog,_pos,_note,_prevNote); + setNote(*_catalog, _pos, _note, _prevNote); } void SetNoteCmd::doUndo() { - Note tmp; setNote(*_catalog,_pos,_prevNote,tmp); + Note tmp; setNote(*_catalog, _pos, _prevNote, tmp); } void SetNoteCmd::setJumpingPos() { - DocPosition pos=_pos; - pos.form=0; + DocPosition pos = _pos; + pos.form = 0; _catalog->setLastModifiedPos(pos); } //END SetNoteCmd //BEGIN UpdatePhaseCmd UpdatePhaseCmd::UpdatePhaseCmd(Catalog *catalog, const Phase& phase) - : QUndoCommand(i18nc("@item Undo action item","Update/add workflow phase")) + : QUndoCommand(i18nc("@item Undo action item", "Update/add workflow phase")) , _catalog(catalog) , _phase(phase) {} void UpdatePhaseCmd::redo() { - _prevPhase=_catalog->updatePhase(_phase); + _prevPhase = _catalog->updatePhase(_phase); } void UpdatePhaseCmd::undo() @@ -309,172 +307,160 @@ //BEGIN SetEquivTransCmd SetEquivTransCmd::SetEquivTransCmd(Catalog *catalog, const DocPosition& pos, bool equivTrans) - : LokalizeTargetCmd(catalog,pos,i18nc("@item Undo action item","Translation Equivalence Setting")) + : LokalizeTargetCmd(catalog, pos, i18nc("@item Undo action item", "Translation Equivalence Setting")) , _equivTrans(equivTrans) {} void SetEquivTransCmd::doRedo() { - _catalog->setEquivTrans(_pos,_equivTrans); + _catalog->setEquivTrans(_pos, _equivTrans); } void SetEquivTransCmd::doUndo() { - _catalog->setEquivTrans(_pos,!_equivTrans); + _catalog->setEquivTrans(_pos, !_equivTrans); } //END SetEquivTransCmd -bool fillTagPlaces(QMap& tagPlaces, +bool fillTagPlaces(QMap& tagPlaces, const CatalogString& catalogString, int start, int len ) { - QString target=catalogString.string; - if (len==-1) - len=target.size(); + QString target = catalogString.string; + if (len == -1) + len = target.size(); - int t=start; - while ((t=target.indexOf(TAGRANGE_IMAGE_SYMBOL,t))!=-1 && t<(start+len)) - tagPlaces[t++]=0; + int t = start; + while ((t = target.indexOf(TAGRANGE_IMAGE_SYMBOL, t)) != -1 && t < (start + len)) + tagPlaces[t++] = 0; - int i=catalogString.tags.size(); - while(--i>=0) - { + int i = catalogString.tags.size(); + while (--i >= 0) { //qCWarning(LOKALIZE_LOG)<::const_iterator it = tagPlaces.constBegin(); + QMap::const_iterator it = tagPlaces.constBegin(); while (it != tagPlaces.constEnd() && it.value()) ++it; - return it==tagPlaces.constEnd(); + return it == tagPlaces.constEnd(); } bool removeTargetSubstring(Catalog* catalog, DocPosition pos, int delStart, int delLen) { - CatalogString targetWithTags=catalog->targetWithTags(pos); - QString target=targetWithTags.string; - qCDebug(LOKALIZE_LOG)<<"called with"<capabilities()&Tags; - QMap tagPlaces; - if (target.isEmpty() || (doTags && !fillTagPlaces(tagPlaces,targetWithTags,delStart,delLen))) - { - qCWarning(LOKALIZE_LOG)<<"error removing text"<targetWithTags(pos); + QString target = targetWithTags.string; + qCDebug(LOKALIZE_LOG) << "called with" << delStart << "delLen" << delLen << "target:" << target; + if (delLen == -1) + delLen = target.length() - delStart; + + bool doTags = catalog->capabilities()&Tags; + QMap tagPlaces; + if (target.isEmpty() || (doTags && !fillTagPlaces(tagPlaces, targetWithTags, delStart, delLen))) { + qCWarning(LOKALIZE_LOG) << "error removing text" << target; return false; } - catalog->beginMacro(i18nc("@item Undo action item","Remove text with markup")); + catalog->beginMacro(i18nc("@item Undo action item", "Remove text with markup")); //all indexes are ok (or target is just plain text) //modified=true; //qCWarning(LOKALIZE_LOG)<<"all indexes are ok"; - QMapIterator it(tagPlaces); + QMapIterator it(tagPlaces); it.toBack(); - while (it.hasPrevious()) - { + while (it.hasPrevious()) { it.previous(); - if (it.value()!=1) continue; - pos.offset=it.key(); - DelTagCmd* cmd=new DelTagCmd(catalog,pos); + if (it.value() != 1) continue; + pos.offset = it.key(); + DelTagCmd* cmd = new DelTagCmd(catalog, pos); catalog->push(cmd); - delLen-=1+cmd->tag().isPaired(); - QString tmp=catalog->targetWithTags(pos).string; + delLen -= 1 + cmd->tag().isPaired(); + QString tmp = catalog->targetWithTags(pos).string; tmp.replace(TAGRANGE_IMAGE_SYMBOL, u'*'); - qCDebug(LOKALIZE_LOG)<<"\tdeleting at"<targetWithTags(pos).string; + QString tmp = catalog->targetWithTags(pos).string; tmp.replace(TAGRANGE_IMAGE_SYMBOL, u'*'); - qCDebug(LOKALIZE_LOG)<<"offset"<targetWithTags(pos).string.mid(delStart,delLen); + qCDebug(LOKALIZE_LOG) << "offset" << delStart << delLen << "current string:" << tmp; + pos.offset = delStart; + if (delLen) { + QString rText = catalog->targetWithTags(pos).string.mid(delStart, delLen); rText.remove(TAGRANGE_IMAGE_SYMBOL); - qCDebug(LOKALIZE_LOG)<<"rText"<push(new DelTextCmd(catalog,pos,rText)); + catalog->push(new DelTextCmd(catalog, pos, rText)); } - tmp=catalog->targetWithTags(pos).string; + tmp = catalog->targetWithTags(pos).string; tmp.replace(TAGRANGE_IMAGE_SYMBOL, u'*'); - qCDebug(LOKALIZE_LOG)<<"current string:"<endMacro(); return true; } void insertCatalogString(Catalog* catalog, DocPosition pos, const CatalogString& catStr, int start) { - QMap posToTag; - int i=catStr.tags.size(); - bool containsMarkup=i; - while(--i>=0) - { - const InlineTag& tag=catStr.tags.at(i); + QMap posToTag; + int i = catStr.tags.size(); + bool containsMarkup = i; + while (--i >= 0) { + const InlineTag& tag = catStr.tags.at(i); //qCWarning(LOKALIZE_LOG)<<"\t"<beginMacro(i18nc("@item Undo action item","Insert text with markup")); + if (containsMarkup) catalog->beginMacro(i18nc("@item Undo action item", "Insert text with markup")); - i=0; - int prev=0; - while ((i = catStr.string.indexOf(TAGRANGE_IMAGE_SYMBOL, i)) != -1) - { - qCDebug(LOKALIZE_LOG)<<"TAGRANGE_IMAGE_SYMBOL"<push(new InsTextCmd(catalog,pos,catStr.string.mid(prev,i-prev))); + if (i - prev) { + pos.offset = start + prev; + catalog->push(new InsTextCmd(catalog, pos, catStr.string.mid(prev, i - prev))); } //now dealing with tag - qCDebug(LOKALIZE_LOG)<<"posToTag.value(i)"<push(new InsTagCmd(catalog,pos,tag)); + qCDebug(LOKALIZE_LOG) << "posToTag.value(i)" << posToTag.value(i) << catStr.tags.size(); + if (posToTag.value(i) < catStr.tags.size()) { + InlineTag tag = catStr.tags.at(posToTag.value(i)); + qCDebug(LOKALIZE_LOG) << i << "testing for tag" << tag.name() << tag.start << tag.start; + if (tag.start == i) { //this is an opening tag (may be single tag) + pos.offset = start + i; + tag.start += start; + tag.end += start; + catalog->push(new InsTagCmd(catalog, pos, tag)); } - } - else - { + } else { //HACK to keep positions in sync - pos.offset=start+i; - catalog->push(new InsTextCmd(catalog,pos,QStringLiteral(" "))); - } - prev=++i; + pos.offset = start + i; + catalog->push(new InsTextCmd(catalog, pos, QStringLiteral(" "))); + } + prev = ++i; } - pos.offset=start+prev; - if (catStr.string.length()-prev>0) - catalog->push(new InsTextCmd(catalog,pos,catStr.string.mid(prev))); + pos.offset = start + prev; + if (catStr.string.length() - prev > 0) + catalog->push(new InsTextCmd(catalog, pos, catStr.string.mid(prev))); if (containsMarkup) catalog->endMacro(); } diff --git a/src/catalog/gettext/catalogfileplugin.h b/src/catalog/gettext/catalogfileplugin.h --- a/src/catalog/gettext/catalogfileplugin.h +++ b/src/catalog/gettext/catalogfileplugin.h @@ -2,8 +2,8 @@ This file is part of KAider This file contains parts of KBabel code - Copyright (C) 2002-2003 by Stanislav Visnovsky - + Copyright (C) 2002-2003 by Stanislav Visnovsky + This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -39,7 +39,8 @@ class QString; class QStringList; -namespace GettextCatalog { +namespace GettextCatalog +{ class GettextStorage; class CatalogItem; @@ -49,8 +50,8 @@ /** * Result of the conversion */ -enum ConversionStatus { - OK=0, +enum ConversionStatus { + OK = 0, NOT_IMPLEMENTED, NO_FILE, NO_PERMISSIONS, @@ -71,8 +72,8 @@ * (when whole DOM-tree is stored in memory to prevent file clashes) * * This class is the base for import plugins for catalogs. - * It provides "transactional behavior", so the changes are stored in - * catalog only if the import process finishes successfully. + * It provides "transactional behavior", so the changes are stored in + * catalog only if the import process finishes successfully. * * To use it, just subclass and redefine load() and id() methods. * When importing, you can use the protected methods for setting @@ -90,7 +91,7 @@ /** * Load the file and fill the corresponding catalog. The file * is considered to be of @ref mimetype MIME type. - * + * * @param file local file name to be opened * @param mimetype the MIME type is should be handled as * @param catalog the catalog to be filled @@ -103,7 +104,7 @@ * Throughout the run, you can use the protected methods for setting * the contents of the resulting catalog. * This method must call \see setMimeTypes to setup correct MIME types - * for the loaded file. Also, it should use \see isStopped to + * for the loaded file. Also, it should use \see isStopped to * abort loading and the signals for providing user feedback. * @param file file to be loaded * @param mimetype the expected MIME type (the type used for plugin selection @@ -115,21 +116,21 @@ * @param item the new item * @param obsolete flag that the item is obsolete */ - void appendCatalogItem( const CatalogItem& item, const bool obsolete = false ); + void appendCatalogItem(const CatalogItem& item, const bool obsolete = false); /** set flag that the file is generated from DocBook */ void setGeneratedFromDocbook(const bool fromDocbook); /** set the list of parse error indexes */ void setErrorIndex(const QList& errors); /** set extra data for the catalog, which can't be stored in * @ref CatalogItem. The format can be arbitrary */ - void setCatalogExtraData( const QStringList& data ); + void setCatalogExtraData(const QStringList& data); /** set the header catalog item */ - void setHeader( const CatalogItem& header ); + void setHeader(const CatalogItem& header); /** Set the character encoding used in the catalog file. */ - void setCodec( QTextCodec* codec ); + void setCodec(QTextCodec* codec); /** start a new transaction. You should never call this method. */ void startTransaction(); diff --git a/src/catalog/gettext/catalogitem.h b/src/catalog/gettext/catalogitem.h --- a/src/catalog/gettext/catalogitem.h +++ b/src/catalog/gettext/catalogitem.h @@ -31,16 +31,17 @@ your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. - + **************************************************************************** */ #ifndef CATALOGITEM_H #define CATALOGITEM_H #include #include "catalogitem_private.h" -namespace GettextCatalog { +namespace GettextCatalog +{ /** * This class represents an entry in a catalog. @@ -60,80 +61,110 @@ CatalogItem(const CatalogItem& item): d(item.d) {} ~CatalogItem() {} - bool isFuzzy() const {return d._fuzzyCached;} //", fuzzy" in comment + bool isFuzzy() const + { + return d._fuzzyCached; //", fuzzy" in comment + } bool isCformat() const; //", c-format" or possible-c-format in comment (from the debug parameter of xgettext) bool isNoCformat() const; //", no-c-format" in comment bool isQtformat() const; //", qt-format" in comment bool isNoQtformat() const; //", no-qt-format" in comment bool isUntranslated() const; bool isUntranslated(uint form) const; - inline bool isPlural() const {return d._plural;} - inline void setPlural(bool plural=true) {d._plural = plural;} + inline bool isPlural() const + { + return d._plural; + } + inline void setPlural(bool plural = true) + { + d._plural = plural; + } void setSyntaxError(bool); /** returns the number of lines, the entry will need in a file */ int totalLines() const; - - /** cleares the item */ - inline void clear() {d.clear();} - const QString& comment() const {return d._comment;} + /** cleares the item */ + inline void clear() + { + d.clear(); + } + + const QString& comment() const + { + return d._comment; + } QString msgctxt(const bool noNewlines = false) const; - const QString& msgid(const int form=0) const{return d.msgid(form);} - const QString& msgstr(const int form=0) const; + const QString& msgid(const int form = 0) const + { + return d.msgid(form); + } + const QString& msgstr(const int form = 0) const; const QVector& msgstrPlural() const; enum Part {Source, Target}; - QStringList allPluralForms(CatalogItem::Part, bool stripNewLines=false) const; - bool prependEmptyForMsgid(const int form=0) const; - bool prependEmptyForMsgstr(const int form=0) const; - bool keepEmptyMsgCtxt() const {return d._keepEmptyMsgCtxt;} + QStringList allPluralForms(CatalogItem::Part, bool stripNewLines = false) const; + bool prependEmptyForMsgid(const int form = 0) const; + bool prependEmptyForMsgstr(const int form = 0) const; + bool keepEmptyMsgCtxt() const + { + return d._keepEmptyMsgCtxt; + } QStringList msgstrAsList() const; void setComment(const QString& com); void setMsgctxt(const QString& msg); - void setMsgid(const QString& msg, const int form=0); + void setMsgid(const QString& msg, const int form = 0); void setMsgid(const QStringList& msg); void setMsgid(const QStringList& msg, bool prependEmptyLine); void setMsgid(const QVector& msg); - void setMsgstr(const QString& msg, const int form=0); + void setMsgstr(const QString& msg, const int form = 0); void setMsgstr(const QStringList& msg); void setMsgstr(const QStringList& msg, bool prependEmptyLine); void setMsgstr(const QVector& msg); - void setValid(bool v) {d._valid=v;} - bool isValid() const {return d._valid;} + void setValid(bool v) + { + d._valid = v; + } + bool isValid() const + { + return d._valid; + } #if 0 - /** - * @return the list of all errors of this item - */ - QStringList errors() const; - - QString nextError() const; - void clearErrors(); - void removeError(const QString& error); - void appendError(const QString& error); - - /** - * makes some sanity checks and set status accordingly - * @return the new status of this item - * @see CatalogItem::Error - * @param accelMarker a char, that marks the keyboard accelerators - * @param contextInfo a regular expression, that determines what is - * the context information - * @param singularPlural a regular expression, that determines what is - * string with singular and plural form + /** + * @return the list of all errors of this item + */ + QStringList errors() const; + + QString nextError() const; + void clearErrors(); + void removeError(const QString& error); + void appendError(const QString& error); + + /** + * makes some sanity checks and set status accordingly + * @return the new status of this item + * @see CatalogItem::Error + * @param accelMarker a char, that marks the keyboard accelerators + * @param contextInfo a regular expression, that determines what is + * the context information + * @param singularPlural a regular expression, that determines what is + * string with singular and plural form * @param neededLines how many lines a string with singular-plural form * must have - */ - int checkErrors(QChar accelMarker, const QRegExp& contextInfo - , const QRegExp& singularPlural, const int neededLines); - + */ + int checkErrors(QChar accelMarker, const QRegExp& contextInfo + , const QRegExp& singularPlural, const int neededLines); + #endif - inline void operator=(const CatalogItem& rhs) {d.assign(rhs.d);} + inline void operator=(const CatalogItem& rhs) + { + d.assign(rhs.d); + } private: CatalogItemPrivate d; diff --git a/src/catalog/gettext/catalogitem.cpp b/src/catalog/gettext/catalogitem.cpp --- a/src/catalog/gettext/catalogitem.cpp +++ b/src/catalog/gettext/catalogitem.cpp @@ -2,8 +2,8 @@ This file is based on the one from KBabel Copyright (C) 1999-2000 by Matthias Kiefer - 2002 by Stanislav Visnovsky - Copyright (C) 2006 by Nicolas GOUTTE + 2002 by Stanislav Visnovsky + Copyright (C) 2006 by Nicolas GOUTTE 2007-2012 by Nick Shaforostoff This program is free software; you can redistribute it and/or modify @@ -43,14 +43,14 @@ QString CatalogItem::msgctxt(const bool noNewlines) const { - QString msgctxt=d._msgctxt; + QString msgctxt = d._msgctxt; if (noNewlines) return msgctxt.replace(QLatin1Char('\n'), QLatin1Char(' ')); //" " or "" ? else return msgctxt; } const QString& CatalogItem::msgstr(const int form) const { - if (Q_LIKELY (form=d._msgidPlural.size()) - d._msgidPlural.resize(form+1); - d._msgidPlural[form]=msg; + if (form >= d._msgidPlural.size()) + d._msgidPlural.resize(form + 1); + d._msgidPlural[form] = msg; } void CatalogItem::setMsgid(const QStringList& msg) { - d._msgidPlural=msg.toVector(); //TODO - for (QVector::iterator it=d._msgidPlural.begin();it!=d._msgidPlural.end();++it) + d._msgidPlural = msg.toVector(); //TODO + for (QVector::iterator it = d._msgidPlural.begin(); it != d._msgidPlural.end(); ++it) it->squeeze(); } void CatalogItem::setMsgid(const QStringList& msg, bool prependEmptyLine) { - d._prependMsgIdEmptyLine=prependEmptyLine; - d._msgidPlural=msg.toVector(); //TODO - for (QVector::iterator it=d._msgidPlural.begin();it!=d._msgidPlural.end();++it) + d._prependMsgIdEmptyLine = prependEmptyLine; + d._msgidPlural = msg.toVector(); //TODO + for (QVector::iterator it = d._msgidPlural.begin(); it != d._msgidPlural.end(); ++it) it->squeeze(); } void CatalogItem::setMsgid(const QVector& msg) { - d._msgidPlural=msg; - for (QVector::iterator it=d._msgidPlural.begin();it!=d._msgidPlural.end();++it) + d._msgidPlural = msg; + for (QVector::iterator it = d._msgidPlural.begin(); it != d._msgidPlural.end(); ++it) it->squeeze(); } void CatalogItem::setMsgstr(const QString& msg, const int form) { - if (form>=d._msgstrPlural.size()) - d._msgstrPlural.resize(form+1); - d._msgstrPlural[form]=msg; + if (form >= d._msgstrPlural.size()) + d._msgstrPlural.resize(form + 1); + d._msgstrPlural[form] = msg; } void CatalogItem::setMsgstr(const QStringList& msg) { //TODO - d._msgstrPlural=msg.toVector(); + d._msgstrPlural = msg.toVector(); } void CatalogItem::setMsgstr(const QStringList& msg, bool prependEmptyLine) { - d._prependMsgStrEmptyLine=prependEmptyLine; - d._msgstrPlural=msg.toVector(); + d._prependMsgStrEmptyLine = prependEmptyLine; + d._msgstrPlural = msg.toVector(); } void CatalogItem::setMsgstr(const QVector& msg) { - d._msgstrPlural=msg; + d._msgstrPlural = msg; } void CatalogItem::setComment(const QString& com) @@ -150,9 +149,9 @@ //QMutexLocker reLock(&reMutex); //avoid crash #281033 //now we have a bigger scale mutex in GettextStorage static QRegExp fuzzyRegExp(QStringLiteral("((?:^|\n)#(?:,[^,]*)*),\\s*fuzzy")); - d._fuzzyCached=com.contains( fuzzyRegExp ); + d._fuzzyCached = com.contains(fuzzyRegExp); } - d._comment=com; + d._comment = com; d._comment.squeeze(); } @@ -176,90 +175,85 @@ { // Allow "possible-c-format" (from xgettext --debug) or "c-format" // Note the regexp (?: ) is similar to () but it does not capture (so it is faster) - return d._comment.indexOf( QRegExp(",\\s*(?:possible-)c-format") ) == -1; + return d._comment.indexOf(QRegExp(",\\s*(?:possible-)c-format")) == -1; } bool CatalogItem::isNoCformat() const { - return d._comment.indexOf( QRegExp(",\\s*no-c-format") ) == -1; + return d._comment.indexOf(QRegExp(",\\s*no-c-format")) == -1; } bool CatalogItem::isQtformat() const { - return d._comment.indexOf( QRegExp(",\\s*qt-format") ) == -1; + return d._comment.indexOf(QRegExp(",\\s*qt-format")) == -1; } bool CatalogItem::isNoQtformat() const { - return d._comment.indexOf( QRegExp(",\\s*no-qt-format") ) == -1; + return d._comment.indexOf(QRegExp(",\\s*no-qt-format")) == -1; } bool CatalogItem::isUntranslated() const { - return d._msgstr.first().isEmpty(); + return d._msgstr.first().isEmpty(); } int CatalogItem::totalLines() const { - int lines=0; - if(!d._comment.isEmpty()) - { - lines = d._comment.count('\n')+1; - } - int msgctxtLines=0; - if(!d._msgctxt.isEmpty()) - { - msgctxtLines=d._msgctxt.count('\n')+1; - } - int msgidLines=0; - QStringList::ConstIterator it; - for(it=d._msgid.begin(); it != d._msgid.end(); ++it) - { - msgidLines += (*it).count('\n')+1; - } - int msgstrLines=0; - for(it=d._msgstr.begin(); it != d._msgstr.end(); ++it) - { - msgstrLines += (*it).count('\n')+1; - } - - if(msgctxtLines>1) - msgctxtLines++; - if(msgidLines>1) - msgidLines++; - if(msgstrLines>1) - msgstrLines++; - - lines+=( msgctxtLines+msgidLines+msgstrLines ); - - return lines; + int lines = 0; + if (!d._comment.isEmpty()) { + lines = d._comment.count('\n') + 1; + } + int msgctxtLines = 0; + if (!d._msgctxt.isEmpty()) { + msgctxtLines = d._msgctxt.count('\n') + 1; + } + int msgidLines = 0; + QStringList::ConstIterator it; + for (it = d._msgid.begin(); it != d._msgid.end(); ++it) { + msgidLines += (*it).count('\n') + 1; + } + int msgstrLines = 0; + for (it = d._msgstr.begin(); it != d._msgstr.end(); ++it) { + msgstrLines += (*it).count('\n') + 1; + } + + if (msgctxtLines > 1) + msgctxtLines++; + if (msgidLines > 1) + msgidLines++; + if (msgstrLines > 1) + msgstrLines++; + + lines += (msgctxtLines + msgidLines + msgstrLines); + + return lines; } void CatalogItem::setSyntaxError(bool on) { - if(on && !d._errors.contains("syntax error")) - d._errors.append("syntax error"); - else - d._errors.removeAll("syntax error"); + if (on && !d._errors.contains("syntax error")) + d._errors.append("syntax error"); + else + d._errors.removeAll("syntax error"); } #endif QStringList CatalogItem::msgstrAsList() const { - if (d._msgstrPlural.isEmpty()) - { - qCWarning(LOKALIZE_LOG)<<"This should never happen!"; + if (d._msgstrPlural.isEmpty()) { + qCWarning(LOKALIZE_LOG) << "This should never happen!"; return QStringList(); } - QStringList list(d._msgstrPlural.first().split('\n', QString::SkipEmptyParts )); + QStringList list(d._msgstrPlural.first().split('\n', QString::SkipEmptyParts)); - if(d._msgstrPlural.first()==QLatin1String("\n")) + if (d._msgstrPlural.first() == QLatin1String("\n")) list.prepend(QString()); - if(list.isEmpty()) + if (list.isEmpty()) list.append(QString()); return list; @@ -269,58 +263,53 @@ void CatalogItem::setFuzzy() { - d._fuzzyCached=true; + d._fuzzyCached = true; - if (d._comment.isEmpty()) - { - d._comment=QStringLiteral("#, fuzzy"); + if (d._comment.isEmpty()) { + d._comment = QStringLiteral("#, fuzzy"); return; } - int p=d._comment.indexOf(QLatin1String("#,")); - if(p!=-1) - { - d._comment.replace(p,2,QStringLiteral("#, fuzzy,")); + int p = d._comment.indexOf(QLatin1String("#,")); + if (p != -1) { + d._comment.replace(p, 2, QStringLiteral("#, fuzzy,")); return; } - QString comment=d._comment; + QString comment = d._comment; static QRegExp a("\\#\\:[^\n]*\n"); - p=a.indexIn(comment); - if (p!=-1) - { - d._comment=comment.insert(p+a.matchedLength(),QLatin1String("#, fuzzy\n")); + p = a.indexIn(comment); + if (p != -1) { + d._comment = comment.insert(p + a.matchedLength(), QLatin1String("#, fuzzy\n")); return; } - p=d._comment.indexOf(QLatin1String("\n#|")); - if (p!=-1) - { - d._comment.insert(p,QLatin1String("\n#, fuzzy")); + p = d._comment.indexOf(QLatin1String("\n#|")); + if (p != -1) { + d._comment.insert(p, QLatin1String("\n#, fuzzy")); return; } - if (d._comment.startsWith(QLatin1String("#|"))) - { + if (d._comment.startsWith(QLatin1String("#|"))) { d._comment.prepend(QLatin1String("#, fuzzy\n")); return; } - if( !(d._comment.endsWith(QLatin1Char('\n'))) ) - d._comment+=QLatin1Char('\n'); - d._comment+=QLatin1String("#, fuzzy"); + if (!(d._comment.endsWith(QLatin1Char('\n')))) + d._comment += QLatin1Char('\n'); + d._comment += QLatin1String("#, fuzzy"); } void CatalogItem::unsetFuzzy() { - d._fuzzyCached=false; + d._fuzzyCached = false; static const QRegExp rmFuzzyRe(QStringLiteral(",\\s*fuzzy")); - d._comment.remove( rmFuzzyRe ); + d._comment.remove(rmFuzzyRe); // remove empty comment lines - d._comment.remove( QRegExp(QStringLiteral("\n#\\s*$")) ); - d._comment.remove( QRegExp(QStringLiteral("^#\\s*$")) ); - d._comment.remove( QRegExp(QStringLiteral("#\\s*\n")) ); - d._comment.remove( QRegExp(QStringLiteral("^#\\s*\n")) ); + d._comment.remove(QRegExp(QStringLiteral("\n#\\s*$"))); + d._comment.remove(QRegExp(QStringLiteral("^#\\s*$"))); + d._comment.remove(QRegExp(QStringLiteral("#\\s*\n"))); + d._comment.remove(QRegExp(QStringLiteral("^#\\s*\n"))); } @@ -337,15 +326,15 @@ d._errors.clear(); } -void CatalogItem::appendError(const QString& error ) +void CatalogItem::appendError(const QString& error) { - if( !d._errors.contains( error ) ) - d._errors.append(error); + if (!d._errors.contains(error)) + d._errors.append(error); } -void CatalogItem::removeError(const QString& error ) +void CatalogItem::removeError(const QString& error) { - d._errors.removeAt( d._errors.indexOf( error ) ); + d._errors.removeAt(d._errors.indexOf(error)); } #endif diff --git a/src/catalog/gettext/catalogitem_private.h b/src/catalog/gettext/catalogitem_private.h --- a/src/catalog/gettext/catalogitem_private.h +++ b/src/catalog/gettext/catalogitem_private.h @@ -4,8 +4,8 @@ Copyright (C) 1999-2000 by Matthias Kiefer - 2002 by Stanislav Visnovsky - 2007-2011 by Nick Shaforostoff + 2002 by Stanislav Visnovsky + 2007-2011 by Nick Shaforostoff This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -31,16 +31,17 @@ your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. - + **************************************************************************** */ #ifndef CATALOGITEMPRIVATE_H #define CATALOGITEMPRIVATE_H #include #include #include -namespace GettextCatalog { +namespace GettextCatalog +{ /** * This class represents data for an entry in a catalog. @@ -93,8 +94,8 @@ inline void CatalogItemPrivate::clear() { - _plural=false; - _valid=true; + _plural = false; + _valid = true; _comment.clear(); _msgctxt.clear(); _msgidPlural.clear(); @@ -105,30 +106,30 @@ inline void CatalogItemPrivate::assign(const CatalogItemPrivate& other) { - _comment=other._comment; - _msgctxt=other._msgctxt; - _msgidPlural=other._msgidPlural; - _msgstrPlural=other._msgstrPlural; - _valid=other._valid; + _comment = other._comment; + _msgctxt = other._msgctxt; + _msgidPlural = other._msgidPlural; + _msgstrPlural = other._msgstrPlural; + _valid = other._valid; //_errors=other._errors; - _plural=other._plural; - _fuzzyCached=other._fuzzyCached; + _plural = other._plural; + _fuzzyCached = other._fuzzyCached; } inline bool CatalogItemPrivate::isUntranslated() const { - int i=_msgstrPlural.size(); - while (--i>=0) + int i = _msgstrPlural.size(); + while (--i >= 0) if (_msgstrPlural.at(i).isEmpty()) return true; return false; } inline bool CatalogItemPrivate::isUntranslated(uint form) const { - if ((int)form<_msgstrPlural.size()) + if ((int)form < _msgstrPlural.size()) return _msgstrPlural.at(form).isEmpty(); else return true; @@ -138,7 +139,7 @@ const QString& CatalogItemPrivate::msgid(const int form) const { //if original lang is english, we have only 2 formz - return (form<_msgidPlural.size())?_msgidPlural.at(form):_msgidPlural.last(); + return (form < _msgidPlural.size()) ? _msgidPlural.at(form) : _msgidPlural.last(); } } diff --git a/src/catalog/gettext/exportplugin.cpp b/src/catalog/gettext/exportplugin.cpp --- a/src/catalog/gettext/exportplugin.cpp +++ b/src/catalog/gettext/exportplugin.cpp @@ -3,7 +3,7 @@ This file is based on the one from KBabel Copyright (C) 2002-2003 by Stanislav Visnovsky - 2007 by Nick Shaforostoff + 2007 by Nick Shaforostoff This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -29,7 +29,7 @@ your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. - + **************************************************************************** */ #include "catalogfileplugin.h" diff --git a/src/catalog/gettext/gettextexport.h b/src/catalog/gettext/gettextexport.h --- a/src/catalog/gettext/gettextexport.h +++ b/src/catalog/gettext/gettextexport.h @@ -40,7 +40,8 @@ #include #include -namespace GettextCatalog { +namespace GettextCatalog +{ class GettextStorage; @@ -53,22 +54,22 @@ class GettextExportPlugin { public: - GettextExportPlugin(short wrapWidth=-1, short trailingNewLines=1); + GettextExportPlugin(short wrapWidth = -1, short trailingNewLines = 1); ConversionStatus save(QIODevice* device, const GettextStorage* catalog, QTextCodec* codec); private: /** * Write a PO comment to @p stream and take care that each comment lines start with a # character */ - void writeComment( QTextStream& stream, const QString& comment ) const; + void writeComment(QTextStream& stream, const QString& comment) const; /** * Write a PO keyword (msgctxt, msgid, msgstr, msgstr_plural, msgstr[0]) and the corresponding text. * This includes wrapping the text. */ - void writeKeyword( QTextStream& stream, const QString& keyword, QString text, bool containsHtml=true, bool startedWithEmptyLine=false ) const; + void writeKeyword(QTextStream& stream, const QString& keyword, QString text, bool containsHtml = true, bool startedWithEmptyLine = false) const; public: /** diff --git a/src/catalog/gettext/gettextexport.cpp b/src/catalog/gettext/gettextexport.cpp --- a/src/catalog/gettext/gettextexport.cpp +++ b/src/catalog/gettext/gettextexport.cpp @@ -3,7 +3,7 @@ This file contains parts of KBabel code Copyright (C) 1999-2000 by Matthias Kiefer - 2001-2002 by Stanislav Visnovsky + 2001-2002 by Stanislav Visnovsky Copyright (C) 2005,2006 by Nicolas GOUTTE This program is free software; you can redistribute it and/or modify @@ -58,271 +58,243 @@ } ConversionStatus GettextExportPlugin::save(QIODevice* device, - const GettextStorage* catalog, - QTextCodec* codec) + const GettextStorage* catalog, + QTextCodec* codec) { QTextStream stream(device); stream.setCodec(codec); //if ( m_wrapWidth == -1 ) m_wrapWidth=80; // only save header if it is not empty - const QString& headerComment( catalog->m_header.comment() ); + const QString& headerComment(catalog->m_header.comment()); // ### why is this useful to have a header with an empty msgstr? - if ( !headerComment.isEmpty() || !catalog->m_header.msgstrPlural().isEmpty() ) - { + if (!headerComment.isEmpty() || !catalog->m_header.msgstrPlural().isEmpty()) { // write header - writeComment( stream, headerComment ); + writeComment(stream, headerComment); - const QString& headerMsgid (catalog->m_header.msgid()); + const QString& headerMsgid(catalog->m_header.msgid()); // Gettext PO files should have an empty msgid as header - if ( !headerMsgid.isEmpty() ) - { + if (!headerMsgid.isEmpty()) { // ### perhaps it is grave enough for a user message qCWarning(LOKALIZE_LOG) << "Non-empty msgid for the header, assuming empty msgid!" << endl << headerMsgid << "---"; } // ### FIXME: if it is the header, then the msgid should be empty! (Even if KBabel has made something out of a non-header first entry!) stream << QStringLiteral("msgid \"\"\n"); - writeKeyword( stream, QStringLiteral("msgstr"), catalog->m_header.msgstr(), false ); + writeKeyword(stream, QStringLiteral("msgstr"), catalog->m_header.msgstr(), false); } - const QVector& catalogEntries=catalog->m_entries; - int limit=catalog->numberOfEntries(); + const QVector& catalogEntries = catalog->m_entries; + int limit = catalog->numberOfEntries(); QStringList list; - for (int counter = 0; counter < limit; counter++) - { + for (int counter = 0; counter < limit; counter++) { stream << '\n'; const CatalogItem& catalogItem = catalogEntries.at(counter); // write entry - writeComment( stream, catalogItem.comment() ); + writeComment(stream, catalogItem.comment()); const QString& msgctxt = catalogItem.msgctxt(); if (! msgctxt.isEmpty() || catalogItem.keepEmptyMsgCtxt()) - writeKeyword( stream, QStringLiteral("msgctxt"), msgctxt ); + writeKeyword(stream, QStringLiteral("msgctxt"), msgctxt); - writeKeyword( stream, QStringLiteral("msgid"), catalogItem.msgid(), true, catalogItem.prependEmptyForMsgid() ); - if ( catalogItem.isPlural() ) - writeKeyword( stream, QStringLiteral("msgid_plural"), catalogItem.msgid(1), true, catalogItem.prependEmptyForMsgid() ); + writeKeyword(stream, QStringLiteral("msgid"), catalogItem.msgid(), true, catalogItem.prependEmptyForMsgid()); + if (catalogItem.isPlural()) + writeKeyword(stream, QStringLiteral("msgid_plural"), catalogItem.msgid(1), true, catalogItem.prependEmptyForMsgid()); if (!catalogItem.isPlural()) - writeKeyword( stream, QStringLiteral("msgstr"), catalogItem.msgstr(), true, catalogItem.prependEmptyForMsgstr() ); - else - { + writeKeyword(stream, QStringLiteral("msgstr"), catalogItem.msgstr(), true, catalogItem.prependEmptyForMsgstr()); + else { qCDebug(LOKALIZE_LOG) << "Saving gettext plural form"; //TODO check len of the actual stringlist?? const int forms = catalog->numberOfPluralForms(); - for ( int i = 0; i < forms; ++i ) - { - QString keyword = QStringLiteral("msgstr[") % QString::number( i ) % ']'; - writeKeyword( stream, keyword, catalogItem.msgstr(i), true, catalogItem.prependEmptyForMsgstr() ); + for (int i = 0; i < forms; ++i) { + QString keyword = QStringLiteral("msgstr[") % QString::number(i) % ']'; + writeKeyword(stream, keyword, catalogItem.msgstr(i), true, catalogItem.prependEmptyForMsgstr()); } } } #if 0 //legacy - if ( _saveSettings.saveObsolete ) + if (_saveSettings.saveObsolete) #endif { QList::const_iterator oit; - const QStringList& _obsolete=catalog->m_catalogExtraData; - oit=_obsolete.constBegin(); - if (oit!=_obsolete.constEnd()) - { + const QStringList& _obsolete = catalog->m_catalogExtraData; + oit = _obsolete.constBegin(); + if (oit != _obsolete.constEnd()) { stream << "\n" << (*oit); - while((++oit)!=_obsolete.constEnd()) + while ((++oit) != _obsolete.constEnd()) stream << "\n\n" << (*oit); } } - int i=m_trailingNewLines+1; - while (--i>=0) + int i = m_trailingNewLines + 1; + while (--i >= 0) stream << '\n'; return OK; } -void GettextExportPlugin::writeComment( QTextStream& stream, const QString& comment ) const +void GettextExportPlugin::writeComment(QTextStream& stream, const QString& comment) const { - if( !comment.isEmpty() ) - { + if (!comment.isEmpty()) { // We must check that each comment line really starts with a #, to avoid syntax errors int pos = 0; - for(;;) - { - const int newpos = comment.indexOf( '\n', pos, Qt::CaseInsensitive ); - if ( newpos == pos ) - { + for (;;) { + const int newpos = comment.indexOf('\n', pos, Qt::CaseInsensitive); + if (newpos == pos) { ++pos; stream << '\n'; continue; } - const QString& span ((newpos==-1 ) ? comment.mid(pos) : comment.mid(pos, newpos-pos) ); + const QString& span((newpos == -1) ? comment.mid(pos) : comment.mid(pos, newpos - pos)); const int len = span.length(); QString spaces; // Stored leading spaces - for ( int i = 0 ; i < len ; ++i ) - { + for (int i = 0 ; i < len ; ++i) { const QChar& ch = span[ i ]; - if ( ch == '#' ) - { - stream << spaces << span.mid( i ); + if (ch == '#') { + stream << spaces << span.mid(i); break; - } - else if ( ch == ' ' || ch == '\t' ) - { + } else if (ch == ' ' || ch == '\t') { // We have a leading white space character, so store it temporary spaces += ch; - } - else - { + } else { // Not leading white space and not a # character. so consider that the # character was missing at first position. - stream << "# " << spaces << span.mid( i ); + stream << "# " << spaces << span.mid(i); break; } } stream << '\n'; - if ( newpos == -1 ) + if (newpos == -1) break; else pos = newpos + 1; } } } -void GettextExportPlugin::writeKeyword( QTextStream& stream, const QString& keyword, QString text, bool containsHtml, bool startedWithEmptyLine ) const +void GettextExportPlugin::writeKeyword(QTextStream& stream, const QString& keyword, QString text, bool containsHtml, bool startedWithEmptyLine) const { - if ( text.isEmpty() ) - { + if (text.isEmpty()) { // Whatever the wrapping mode, an empty line is an empty line stream << keyword << QStringLiteral(" \"\"\n"); return; } - text.replace(QLatin1Char('"'),QStringLiteral("\\\"")); + text.replace(QLatin1Char('"'), QStringLiteral("\\\"")); #if 0 - if ( m_wrapWidth == -1 ) - { + if (m_wrapWidth == -1) { // Traditional KBabel wrapping - QStringList list = text.split( '\n', QString::SkipEmptyParts ); + QStringList list = text.split('\n', QString::SkipEmptyParts); - if ( text.startsWith( '\n' ) ) - list.prepend( QString() ); + if (text.startsWith('\n')) + list.prepend(QString()); - if(list.isEmpty()) - list.append( QString() ); + if (list.isEmpty()) + list.append(QString()); - if( list.count() > 1 ) - list.prepend( QString() ); + if (list.count() > 1) + list.prepend(QString()); stream << keyword << ' '; QStringList::const_iterator it; - for( it = list.constBegin(); it != list.constEnd(); ++it ) + for (it = list.constBegin(); it != list.constEnd(); ++it) stream << '\"' << (*it) << "\"\n"; return; } #endif - if ( m_wrapWidth == 0 ) // Unknown special wrapping, so assume "no wrap" instead - { + if (m_wrapWidth == 0) { // Unknown special wrapping, so assume "no wrap" instead // No wrapping (like Gettext's --no.wrap or -w0 ) // we need to remove the \n characters, as they are extra characters - QString realText( text ); - realText.remove( '\n' ); + QString realText(text); + realText.remove('\n'); stream << keyword << " \"" << realText << "\"\n"; return; - } - else if ( m_wrapWidth <= 3 ) - { + } else if (m_wrapWidth <= 3) { // No change in wrapping - QStringList list = text.split( '\n'); - if (list.count()>1 || startedWithEmptyLine /* || keyword.length()+3+text.length()>=80*/) + QStringList list = text.split('\n'); + if (list.count() > 1 || startedWithEmptyLine /* || keyword.length()+3+text.length()>=80*/) list.prepend(QString()); stream << keyword << QStringLiteral(" "); QStringList::const_iterator it; - for( it = list.constBegin(); it != list.constEnd(); ++it ) + for (it = list.constBegin(); it != list.constEnd(); ++it) stream << QStringLiteral("\"") << (*it) << QStringLiteral("\"\n"); return; } // lazy wrapping - QStringList list = text.split( '\n', QString::SkipEmptyParts ); + QStringList list = text.split('\n', QString::SkipEmptyParts); - if ( text.startsWith( '\n' ) ) - list.prepend( QString() ); + if (text.startsWith('\n')) + list.prepend(QString()); - if(list.isEmpty()) - list.append( QString() ); + if (list.isEmpty()) + list.append(QString()); //static QRegExp breakStopReForHtml("[ >.%/:,]", Qt::CaseSensitive, QRegExp::Wildcard); //static QRegExp breakStopReForText("[ .%/:,]", Qt::CaseSensitive, QRegExp::Wildcard); static QRegExp breakStopReForHtml(QStringLiteral("[ >%]"), Qt::CaseSensitive, QRegExp::Wildcard); static QRegExp breakStopReForText(QStringLiteral("[ &%]"), Qt::CaseSensitive, QRegExp::Wildcard); - QRegExp breakStopRe=containsHtml?breakStopReForHtml:breakStopReForText; + QRegExp breakStopRe = containsHtml ? breakStopReForHtml : breakStopReForText; - int max=m_wrapWidth-2; - bool prependedEmptyLine=false; + int max = m_wrapWidth - 2; + bool prependedEmptyLine = false; QStringList::iterator itm; - for( itm = list.begin(); itm != list.end(); ++itm ) - { - if (list.count()==1 && keyword.length()+1+itm->length()>=max) - { - prependedEmptyLine=true; - itm=list.insert(itm,QString()); + for (itm = list.begin(); itm != list.end(); ++itm) { + if (list.count() == 1 && keyword.length() + 1 + itm->length() >= max) { + prependedEmptyLine = true; + itm = list.insert(itm, QString()); } - if (itm->length()>max) - { - int pos = itm->lastIndexOf(breakStopRe,max-1); - if (pos>(max/2)) - { - int pos2 = itm->indexOf(QLatin1Char('<'),pos); - if (pos2>0&&pos2indexOf(QLatin1Char('<'),pos); + if (itm->length() > max) { + int pos = itm->lastIndexOf(breakStopRe, max - 1); + if (pos > (max / 2)) { + int pos2 = itm->indexOf(QLatin1Char('<'), pos); + if (pos2 > 0 && pos2 < max - 1) { + pos = itm->indexOf(QLatin1Char('<'), pos); ++pos; } - } - else - { - if (itm->at(max-1)==QLatin1Char('\\')) - { - do {--max;} - while (max>=2 && itm->at(max-1)==QLatin1Char('\\')); + } else { + if (itm->at(max - 1) == QLatin1Char('\\')) { + do { + --max; + } while (max >= 2 && itm->at(max - 1) == QLatin1Char('\\')); } - pos=max; + pos = max; //Restore the max variable to the m_wordWrap - 2 value - max=m_wrapWidth-2; + max = m_wrapWidth - 2; } //itm=list.insert(itm,itm->left(pos)); - QString t=*itm; - itm=list.insert(itm,t); + QString t = *itm; + itm = list.insert(itm, t); ++itm; - if (itm != list.end()) - { - (*itm)=itm->remove(0,pos); + if (itm != list.end()) { + (*itm) = itm->remove(0, pos); --itm; if (itm != list.end()) itm->truncate(pos); } } } - if( !prependedEmptyLine && list.count() > 1 ) - list.prepend( QString() ); + if (!prependedEmptyLine && list.count() > 1) + list.prepend(QString()); stream << keyword << QStringLiteral(" "); QStringList::const_iterator it; - for( it = list.constBegin(); it != list.constEnd(); ++it ) + for (it = list.constBegin(); it != list.constEnd(); ++it) stream << QStringLiteral("\"") << (*it) << QStringLiteral("\"\n"); } diff --git a/src/catalog/gettext/gettextimport.h b/src/catalog/gettext/gettextimport.h --- a/src/catalog/gettext/gettextimport.h +++ b/src/catalog/gettext/gettextimport.h @@ -43,26 +43,30 @@ class QTextCodec; -namespace GettextCatalog { +namespace GettextCatalog +{ class ExtraDataSaver { public: - ExtraDataSaver(){} - virtual ~ExtraDataSaver(){} - void operator()(const QString& comment){extraData.append(comment);} + ExtraDataSaver() {} + virtual ~ExtraDataSaver() {} + void operator()(const QString& comment) + { + extraData.append(comment); + } QStringList extraData; }; -class ExtraDataSkipSaver:public ExtraDataSaver +class ExtraDataSkipSaver: public ExtraDataSaver { public: - ExtraDataSkipSaver(){} - void operator()(const QString&){}; + ExtraDataSkipSaver() {} + void operator()(const QString&) {}; }; /** - * The class for importing GNU gettext PO files. + * The class for importing GNU gettext PO files. * As an extra information, it stores the list of all obsolete entries. * @short Gettext PO parser */ @@ -74,7 +78,10 @@ //GettextImportPlugin(ExtraDataSaver* extraDataSaver); //~GettextImportPlugin(){delete _extraDataSaver;} ConversionStatus load(QIODevice*); - const QString id() {return "GNU gettext";} + const QString id() + { + return "GNU gettext"; + } private: QTextCodec* codecForDevice(QIODevice* /*, bool* hadCodec*/); diff --git a/src/catalog/gettext/gettextimport.cpp b/src/catalog/gettext/gettextimport.cpp --- a/src/catalog/gettext/gettextimport.cpp +++ b/src/catalog/gettext/gettextimport.cpp @@ -57,745 +57,645 @@ // : CatalogImportPlugin() // , _extraDataSaver(extraDataSaver) GettextImportPlugin::GettextImportPlugin() - : CatalogImportPlugin() - , _msgidMultiline(false) - , _msgstrMultiline(false) - , _gettextPluralForm(false) - , _testBorked(false) - , _obsolete(false) - , _msgctxtPresent(false) - , _rxMsgCtxt (QStringLiteral("^msgctxt\\s*\".*\"$")) - , _rxMsgId (QStringLiteral("^msgid\\s*\".*\"$")) - , _rxMsgIdPlural (QStringLiteral("^msgid_plural\\s*\".*\"$")) - , _rxMsgIdPluralBorked(QStringLiteral("^msgid_plural\\s*\"?.*\"?$")) - , _rxMsgIdBorked (QStringLiteral("^msgid\\s*\"?.*\"?$")) - , _rxMsgIdRemQuotes (QStringLiteral("^msgid\\s*\"")) - , _rxMsgLineRemEndQuote (QStringLiteral("\"$")) - , _rxMsgLineRemStartQuote (QStringLiteral("^\"")) - , _rxMsgLine (QStringLiteral("^\".*\\n?\"$")) - , _rxMsgLineBorked (QStringLiteral("^\"?.+\\n?\"?$")) - , _rxMsgStr (QStringLiteral("^msgstr\\s*\".*\\n?\"$")) - , _rxMsgStrOther (QStringLiteral("^msgstr\\s*\"?.*\\n?\"?$")) - , _rxMsgStrPluralStart(QStringLiteral("^msgstr\\[0\\]\\s*\".*\\n?\"$")) - , _rxMsgStrPluralStartBorked (QStringLiteral("^msgstr\\[0\\]\\s*\"?.*\\n?\"?$")) - , _rxMsgStrPlural (QStringLiteral("^msgstr\\[[0-9]+\\]\\s*\".*\\n?\"$")) - , _rxMsgStrPluralBorked (QStringLiteral("^msgstr\\[[0-9]\\]\\s*\"?.*\\n?\"?$")) - , _rxMsgStrRemQuotes (QStringLiteral("^msgstr\\s*\"?")) + : CatalogImportPlugin() + , _msgidMultiline(false) + , _msgstrMultiline(false) + , _gettextPluralForm(false) + , _testBorked(false) + , _obsolete(false) + , _msgctxtPresent(false) + , _rxMsgCtxt(QStringLiteral("^msgctxt\\s*\".*\"$")) + , _rxMsgId(QStringLiteral("^msgid\\s*\".*\"$")) + , _rxMsgIdPlural(QStringLiteral("^msgid_plural\\s*\".*\"$")) + , _rxMsgIdPluralBorked(QStringLiteral("^msgid_plural\\s*\"?.*\"?$")) + , _rxMsgIdBorked(QStringLiteral("^msgid\\s*\"?.*\"?$")) + , _rxMsgIdRemQuotes(QStringLiteral("^msgid\\s*\"")) + , _rxMsgLineRemEndQuote(QStringLiteral("\"$")) + , _rxMsgLineRemStartQuote(QStringLiteral("^\"")) + , _rxMsgLine(QStringLiteral("^\".*\\n?\"$")) + , _rxMsgLineBorked(QStringLiteral("^\"?.+\\n?\"?$")) + , _rxMsgStr(QStringLiteral("^msgstr\\s*\".*\\n?\"$")) + , _rxMsgStrOther(QStringLiteral("^msgstr\\s*\"?.*\\n?\"?$")) + , _rxMsgStrPluralStart(QStringLiteral("^msgstr\\[0\\]\\s*\".*\\n?\"$")) + , _rxMsgStrPluralStartBorked(QStringLiteral("^msgstr\\[0\\]\\s*\"?.*\\n?\"?$")) + , _rxMsgStrPlural(QStringLiteral("^msgstr\\[[0-9]+\\]\\s*\".*\\n?\"$")) + , _rxMsgStrPluralBorked(QStringLiteral("^msgstr\\[[0-9]\\]\\s*\"?.*\\n?\"?$")) + , _rxMsgStrRemQuotes(QStringLiteral("^msgstr\\s*\"?")) // , _rxMsgId (QStringLiteral("^msgid\\s*\"?.*\"?$")) - , _obsoleteStart(QStringLiteral("#~")) - , _msgctxtStart(QStringLiteral("msgctxt")) + , _obsoleteStart(QStringLiteral("#~")) + , _msgctxtStart(QStringLiteral("msgctxt")) { } ConversionStatus GettextImportPlugin::load(QIODevice* device) { - _testBorked=false; - _errorLine=0; - - // find codec for file - // bool hadCodec; - QTextCodec* codec=codecForDevice(device/*, &hadCodec*/ ); - QTextStream stream(device); - stream.seek(0); - stream.setCodec(codec); - - //QIODevice *dev = stream.device(); - //int fileSize = dev->size(); - - // if somethings goes wrong with the parsing, we don't have deleted the old contents - CatalogItem tempHeader; - - //qCDebug(LOKALIZE_LOG) << "start parsing..."; - QTime aaa; - aaa.start(); - // first read header - const ConversionStatus status = readEntry(stream); - - bool recoveredErrorInHeader = false; - if (Q_UNLIKELY( status == RECOVERED_PARSE_ERROR )) - { - qCDebug(LOKALIZE_LOG) << "Recovered error in header entry"; - recoveredErrorInHeader = true; - } - else if (Q_UNLIKELY( status != OK )) - { - qCWarning(LOKALIZE_LOG) << "Parse error in header entry"; - return status; - } - - bool reconstructedHeader=!_msgid.isEmpty() && !_msgid.first().isEmpty(); - //qCWarning(LOKALIZE_LOG) << "HEADER MSGID: " << _msgid; - //qCWarning(LOKALIZE_LOG) << "HEADER MSGSTR: " << _msgstr; - if (Q_UNLIKELY( reconstructedHeader )) - { - // The header must have an empty msgid - qCWarning(LOKALIZE_LOG) << "Header entry has non-empty msgid. Creating a temporary header! " << _msgid; - tempHeader.setMsgid( QString() ); - QString tmp( - "Content-Type: text/plain; charset=UTF-8\\n" // Unknown charset - "Content-Transfer-Encoding: 8bit\\n" - "Mime-Version: 1.0" ); - tempHeader.setMsgstr( tmp); - // We keep the comment of the first entry, as it might really be a header comment (at least partially) - const QString comment( "# Header entry was created by Lokalize.\n#\n" + _comment ); - tempHeader.setComment( comment ); - recoveredErrorInHeader = true; - } - else - { - tempHeader.setMsgid( _msgid ); - tempHeader.setMsgstr( _msgstr ); - tempHeader.setComment( _comment ); - } + _testBorked = false; + _errorLine = 0; + + // find codec for file + // bool hadCodec; + QTextCodec* codec = codecForDevice(device/*, &hadCodec*/); + QTextStream stream(device); + stream.seek(0); + stream.setCodec(codec); + + //QIODevice *dev = stream.device(); + //int fileSize = dev->size(); + + // if somethings goes wrong with the parsing, we don't have deleted the old contents + CatalogItem tempHeader; + + //qCDebug(LOKALIZE_LOG) << "start parsing..."; + QTime aaa; + aaa.start(); + // first read header + const ConversionStatus status = readEntry(stream); + + bool recoveredErrorInHeader = false; + if (Q_UNLIKELY(status == RECOVERED_PARSE_ERROR)) { + qCDebug(LOKALIZE_LOG) << "Recovered error in header entry"; + recoveredErrorInHeader = true; + } else if (Q_UNLIKELY(status != OK)) { + qCWarning(LOKALIZE_LOG) << "Parse error in header entry"; + return status; + } + + bool reconstructedHeader = !_msgid.isEmpty() && !_msgid.first().isEmpty(); + //qCWarning(LOKALIZE_LOG) << "HEADER MSGID: " << _msgid; + //qCWarning(LOKALIZE_LOG) << "HEADER MSGSTR: " << _msgstr; + if (Q_UNLIKELY(reconstructedHeader)) { + // The header must have an empty msgid + qCWarning(LOKALIZE_LOG) << "Header entry has non-empty msgid. Creating a temporary header! " << _msgid; + tempHeader.setMsgid(QString()); + QString tmp( + "Content-Type: text/plain; charset=UTF-8\\n" // Unknown charset + "Content-Transfer-Encoding: 8bit\\n" + "Mime-Version: 1.0"); + tempHeader.setMsgstr(tmp); + // We keep the comment of the first entry, as it might really be a header comment (at least partially) + const QString comment("# Header entry was created by Lokalize.\n#\n" + _comment); + tempHeader.setComment(comment); + recoveredErrorInHeader = true; + } else { + tempHeader.setMsgid(_msgid); + tempHeader.setMsgstr(_msgstr); + tempHeader.setComment(_comment); + } // if(tempHeader.isFuzzy()) // { // tempHeader.removeFuzzy(); // } - // check if header seems to indicate docbook content generated by xml2pot - const bool docbookContent = tempHeader.msgstr().contains( "application/x-xml2pot" ); + // check if header seems to indicate docbook content generated by xml2pot + const bool docbookContent = tempHeader.msgstr().contains("application/x-xml2pot"); - // now parse the rest of the file - uint counter=0; - QList errorIndex; - //bool recoveredError=false; - bool docbookFile=false; + // now parse the rest of the file + uint counter = 0; + QList errorIndex; + //bool recoveredError=false; + bool docbookFile = false; - ExtraDataSaver _extraDataSaver; - ConversionStatus success=OK; - while( !stream.atEnd() ) - { - if (reconstructedHeader) - reconstructedHeader=false; - else - success=readEntry(stream); + ExtraDataSaver _extraDataSaver; + ConversionStatus success = OK; + while (!stream.atEnd()) { + if (reconstructedHeader) + reconstructedHeader = false; + else + success = readEntry(stream); - if(Q_LIKELY(success==OK)) - { - if( _obsolete ) - _extraDataSaver(_comment); - else - { - CatalogItem tempCatItem; - tempCatItem.setPlural(_gettextPluralForm); - tempCatItem.setMsgid( _msgid, _msgidMultiline ); - tempCatItem.setMsgstr( _msgstr, _msgstrMultiline ); - if (_msgctxtPresent) tempCatItem.setMsgctxt( _msgctxt ); - tempCatItem.setComment( _comment ); - - // add new entry to the list of entries - appendCatalogItem(tempCatItem); - // check if first comment seems to indicate a docbook source file - if(counter==0) - docbookFile = tempCatItem.comment().contains(".docbook" ); - } - } - else if(Q_UNLIKELY( success==RECOVERED_PARSE_ERROR )) - { - qCDebug(LOKALIZE_LOG) << "Recovered parse error in entry: " << counter; - //recoveredError=true; - errorIndex.append(counter); + if (Q_LIKELY(success == OK)) { + if (_obsolete) + _extraDataSaver(_comment); + else { + CatalogItem tempCatItem; + tempCatItem.setPlural(_gettextPluralForm); + tempCatItem.setMsgid(_msgid, _msgidMultiline); + tempCatItem.setMsgstr(_msgstr, _msgstrMultiline); + if (_msgctxtPresent) tempCatItem.setMsgctxt(_msgctxt); + tempCatItem.setComment(_comment); + + // add new entry to the list of entries + appendCatalogItem(tempCatItem); + // check if first comment seems to indicate a docbook source file + if (counter == 0) + docbookFile = tempCatItem.comment().contains(".docbook"); + } + } else if (Q_UNLIKELY(success == RECOVERED_PARSE_ERROR)) { + qCDebug(LOKALIZE_LOG) << "Recovered parse error in entry: " << counter; + //recoveredError=true; + errorIndex.append(counter); CatalogItem tempCatItem; tempCatItem.setPlural(_gettextPluralForm); - tempCatItem.setMsgid( _msgid ); - tempCatItem.setMsgstr( _msgstr ); - if (_msgctxtPresent) tempCatItem.setMsgctxt( _msgctxt ); - tempCatItem.setComment( _comment ); - - - // add new entry to the list of entries - appendCatalogItem(tempCatItem); - } - else if (success == PARSE_ERROR) - { - qCDebug(LOKALIZE_LOG) << "Parse error in entry: " << counter; - return PARSE_ERROR; - } - else - { - qCDebug(LOKALIZE_LOG) << "Unknown success status, assumig parse error " << success; - return PARSE_ERROR; - } - counter++; - - } - - // TODO: can we check that there is no useful entry? - if (Q_UNLIKELY( !counter && !recoveredErrorInHeader )) - { - // Empty file? (Otherwise, there would be a try of getting an entry and the count would be 1 !) - qCDebug(LOKALIZE_LOG) << " Empty file?"; - return PARSE_ERROR; - } - - //qCDebug(LOKALIZE_LOG) << " ready"; - - // We have successfully loaded the file (perhaps with recovered errors) + tempCatItem.setMsgid(_msgid); + tempCatItem.setMsgstr(_msgstr); + if (_msgctxtPresent) tempCatItem.setMsgctxt(_msgctxt); + tempCatItem.setComment(_comment); + + + // add new entry to the list of entries + appendCatalogItem(tempCatItem); + } else if (success == PARSE_ERROR) { + qCDebug(LOKALIZE_LOG) << "Parse error in entry: " << counter; + return PARSE_ERROR; + } else { + qCDebug(LOKALIZE_LOG) << "Unknown success status, assumig parse error " << success; + return PARSE_ERROR; + } + counter++; + + } + + // TODO: can we check that there is no useful entry? + if (Q_UNLIKELY(!counter && !recoveredErrorInHeader)) { + // Empty file? (Otherwise, there would be a try of getting an entry and the count would be 1 !) + qCDebug(LOKALIZE_LOG) << " Empty file?"; + return PARSE_ERROR; + } + + //qCDebug(LOKALIZE_LOG) << " ready"; + + // We have successfully loaded the file (perhaps with recovered errors) // qCWarning(LOKALIZE_LOG) << " done in " << aaa.elapsed() <<_extraDataSaver->extraData.size() << endl; - setGeneratedFromDocbook(docbookContent || docbookFile); - setHeader(tempHeader); - setCatalogExtraData(_extraDataSaver.extraData); - setErrorIndex(errorIndex); - setCodec(codec); - //setMimeTypes( "text/x-gettext-translation" ); + setGeneratedFromDocbook(docbookContent || docbookFile); + setHeader(tempHeader); + setCatalogExtraData(_extraDataSaver.extraData); + setErrorIndex(errorIndex); + setCodec(codec); + //setMimeTypes( "text/x-gettext-translation" ); #if 0 - if (Q_UNLIKELY( recoveredErrorInHeader )) - { - qCDebug(LOKALIZE_LOG) << " Returning: header error"; - return RECOVERED_HEADER_ERROR; - } - else if (Q_UNLIKELY( recoveredError )) - { - qCDebug(LOKALIZE_LOG) << " Returning: recovered parse error"; - return RECOVERED_PARSE_ERROR; - } - else + if (Q_UNLIKELY(recoveredErrorInHeader)) { + qCDebug(LOKALIZE_LOG) << " Returning: header error"; + return RECOVERED_HEADER_ERROR; + } else if (Q_UNLIKELY(recoveredError)) { + qCDebug(LOKALIZE_LOG) << " Returning: recovered parse error"; + return RECOVERED_PARSE_ERROR; + } else #endif - { - //qCDebug(LOKALIZE_LOG) << " Returning: OK! :-)"; - return OK; - } + { + //qCDebug(LOKALIZE_LOG) << " Returning: OK! :-)"; + return OK; + } } QTextCodec* GettextImportPlugin::codecForDevice(QIODevice* device/*, bool* hadCodec*/) { - QTextStream stream( device ); + QTextStream stream(device); stream.seek(0); - _errorLine=0; - stream.setCodec( "UTF-8" ); + _errorLine = 0; + stream.setCodec("UTF-8"); stream.setAutoDetectUnicode(true); //this way we can - QTextCodec* codec=stream.codec(); //detect UTF-16 + QTextCodec* codec = stream.codec(); //detect UTF-16 ConversionStatus status = readEntry(stream); - if (Q_UNLIKELY( status!=OK && status != RECOVERED_PARSE_ERROR )) - { + if (Q_UNLIKELY(status != OK && status != RECOVERED_PARSE_ERROR)) { qCDebug(LOKALIZE_LOG) << "wasn't able to read header"; return codec; } QRegExp regexp(QStringLiteral("Content-Type:\\s*\\w+/[-\\w]+;?\\s*charset\\s*=\\s*(\\S+)\\s*\\\\n")); - if ( regexp.indexIn( _msgstr.first() ) == -1 ) - { + if (regexp.indexIn(_msgstr.first()) == -1) { qCDebug(LOKALIZE_LOG) << "no charset entry found"; return codec; } const QString charset = regexp.cap(1); - if (charset!=QLatin1String("UTF-8")) qCDebug(LOKALIZE_LOG) << "charset:" << charset; + if (charset != QLatin1String("UTF-8")) qCDebug(LOKALIZE_LOG) << "charset:" << charset; - if (charset.isEmpty()) - { + if (charset.isEmpty()) { qCWarning(LOKALIZE_LOG) << "No charset defined! Assuming UTF-8!"; return codec; } // "CHARSET" is the default charset entry in a template (pot). // characters in a template should be either pure ascii or // at least utf8, so utf8-codec can be used for both. - if ( charset.contains(QLatin1String("CHARSET"))) - { + if (charset.contains(QLatin1String("CHARSET"))) { qCDebug(LOKALIZE_LOG) << QString("file seems to be a template: using utf-8 encoding."); return QTextCodec::codecForName("utf8");; } - QTextCodec* t=0; + QTextCodec* t = 0; t = QTextCodec::codecForName(charset.toLatin1()); if (t) return t; else - qCWarning(LOKALIZE_LOG) << "charset found, but no codec available, using UTF-8 instead"; + qCWarning(LOKALIZE_LOG) << "charset found, but no codec available, using UTF-8 instead"; return codec;//UTF-8 } ConversionStatus GettextImportPlugin::readEntry(QTextStream& stream) { - ConversionStatus result=readEntryRaw(stream); - const QString FROM = QStringLiteral("\\\""); - const QString TO = QStringLiteral("\""); - _msgstr.replaceInStrings(FROM, TO); - _msgid.replaceInStrings(FROM, TO); - _msgctxt.replace(FROM, TO); - return result; + ConversionStatus result = readEntryRaw(stream); + const QString FROM = QStringLiteral("\\\""); + const QString TO = QStringLiteral("\""); + _msgstr.replaceInStrings(FROM, TO); + _msgid.replaceInStrings(FROM, TO); + _msgctxt.replace(FROM, TO); + return result; } ConversionStatus GettextImportPlugin::readEntryRaw(QTextStream& stream) { - //qCDebug(LOKALIZE_LOG) << " START"; - enum {Begin,Comment,Msgctxt,Msgid,Msgstr} part=Begin; - - _trailingNewLines=0; - bool error=false; - bool recoverableError=false; - //bool seenMsgctxt=false; - _msgstr.clear(); - _msgstr.append(QString()); - _msgid.clear(); - _msgid.append(QString()); - _msgctxt.clear(); - _msgctxtPresent=false; - _comment.clear(); - _gettextPluralForm=false; - _obsolete=false; - - QStringList::Iterator msgstrIt=_msgstr.begin(); - QString line; - - while( !stream.atEnd() ) - { - _errorLine++; - //line=stream.readLine(); - if (!_bufferedLine.isEmpty()) - { - line=_bufferedLine; + //qCDebug(LOKALIZE_LOG) << " START"; + enum {Begin, Comment, Msgctxt, Msgid, Msgstr} part = Begin; + + _trailingNewLines = 0; + bool error = false; + bool recoverableError = false; + //bool seenMsgctxt=false; + _msgstr.clear(); + _msgstr.append(QString()); + _msgid.clear(); + _msgid.append(QString()); + _msgctxt.clear(); + _msgctxtPresent = false; + _comment.clear(); + _gettextPluralForm = false; + _obsolete = false; + + QStringList::Iterator msgstrIt = _msgstr.begin(); + QString line; + + while (!stream.atEnd()) { + _errorLine++; + //line=stream.readLine(); + if (!_bufferedLine.isEmpty()) { + line = _bufferedLine; _bufferedLine.clear(); - } - else - line=stream.readLine(); - - static const QString lesslessless=QStringLiteral("<<<<<<<"); - static const QString isisis=QStringLiteral("======="); - static const QString moremoremore=QStringLiteral(">>>>>>>"); - if (Q_UNLIKELY( line.startsWith( lesslessless ) || line.startsWith( isisis ) || line.startsWith( moremoremore ) )) - { - // We have found a CVS/SVN conflict marker. Abort. - // (It cannot be any useful data of the PO file, as otherwise the line would start with at least a quote) - qCWarning(LOKALIZE_LOG) << "CVS/SVN conflict marker found! Aborting!" << endl << line << endl; - return PARSE_ERROR; - } - - // remove whitespaces from beginning and end of line - line = line.trimmed(); - - // remember wrapping state to save file nicely - int len=line.length(); - if (len) - { - _trailingNewLines=0; - if (_maxLineLength>>>>>>"); + if (Q_UNLIKELY(line.startsWith(lesslessless) || line.startsWith(isisis) || line.startsWith(moremoremore))) { + // We have found a CVS/SVN conflict marker. Abort. + // (It cannot be any useful data of the PO file, as otherwise the line would start with at least a quote) + qCWarning(LOKALIZE_LOG) << "CVS/SVN conflict marker found! Aborting!" << endl << line << endl; + return PARSE_ERROR; } - else if(part==Msgctxt) - { - if(!len) - continue; - else if( line.contains( _rxMsgLine ) ) - { - // remove quotes at beginning and the end of the lines - line.remove(_rxMsgLineRemStartQuote); - line.remove(_rxMsgLineRemEndQuote); - - // add Msgctxt line to item - if(_msgctxt.isEmpty()) - _msgctxt=line; - else - _msgctxt+=('\n'+line); - _msgctxtPresent=true; - } - else if( line.contains( _rxMsgId ) ) - { - part=Msgid; - // remove quotes at beginning and the end of the lines - line.remove(_rxMsgIdRemQuotes); - line.remove(_rxMsgLineRemEndQuote); + // remove whitespaces from beginning and end of line + line = line.trimmed(); + + // remember wrapping state to save file nicely + int len = line.length(); + if (len) { + _trailingNewLines = 0; + if (_maxLineLength < len && line.at(0) != '#') + _maxLineLength = len; + } else + ++_trailingNewLines; + + + if (part == Begin) { + // ignore trailing newlines + if (!len) + continue; + + if (line.startsWith(_obsoleteStart)) { + _obsolete = true; + part = Comment; + _comment = line; + } else if (line.startsWith('#')) { + part = Comment; + _comment = line; + } else if (line.startsWith(_msgctxtStart) && line.contains(_rxMsgCtxt)) { + part = Msgctxt; + + // remove quotes at beginning and the end of the lines + line.remove(QRegExp(QStringLiteral("^msgctxt\\s*\""))); + line.remove(_rxMsgLineRemEndQuote); + _msgctxt = line; + _msgctxtPresent = true; + //seenMsgctxt=true; + } else if (line.contains(_rxMsgId)) { + part = Msgid; + + // remove quotes at beginning and the end of the lines + line.remove(_rxMsgIdRemQuotes); + line.remove(_rxMsgLineRemEndQuote); + + _msgidMultiline = line.isEmpty(); + (*(_msgid).begin()) = line; - _msgidMultiline=line.isEmpty(); - (*(_msgid).begin())=line; } // one of the quotation marks is missing - else if(Q_UNLIKELY(/*_testBorked&&*/ line.contains ( _rxMsgIdBorked ) )) - { - part=Msgid; - - // remove quotes at beginning and the end of the lines - line.remove(QRegExp(QStringLiteral("^msgid\\s*\"?"))); - line.remove(_rxMsgLineRemEndQuote); - - _msgidMultiline=line.isEmpty(); - (*(_msgid).begin())=line; - - if(!line.isEmpty()) - recoverableError=true; + else if (Q_UNLIKELY(/*_testBorked&&*/ line.contains(_rxMsgIdBorked))) { + part = Msgid; + + // remove quotes at beginning and the end of the lines + line.remove(QRegExp(QStringLiteral("^msgid\\s*\"?"))); + line.remove(_rxMsgLineRemEndQuote); + + _msgidMultiline = line.isEmpty(); + (*(_msgid).begin()) = line; + + if (!line.isEmpty()) + recoverableError = true; + } else { + qCDebug(LOKALIZE_LOG) << "no comment, msgctxt or msgid found after a comment: " << line; + error = true; + break; } - else - { - qCDebug(LOKALIZE_LOG) << "no msgid found after a msgctxt while parsing: " << _msgctxt; - error=true; - break; - } - } - else if(part==Msgid) - { - if(!len) - continue; - else if( line.contains( _rxMsgLine ) ) - { - // remove quotes at beginning and the end of the lines - line.remove(_rxMsgLineRemStartQuote); - line.remove(_rxMsgLineRemEndQuote); - - QStringList::Iterator it; - if(_gettextPluralForm) - { - it=_msgid.end(); - --it; - } - else - it = _msgid.begin(); - - // add Msgid line to item - if(it->isEmpty()) - (*it)=line; - else - (*it)+=('\n'+line); - } - else if( line.contains( _rxMsgIdPlural) ) - { - part=Msgid; - _gettextPluralForm = true; - - // remove quotes at beginning and the end of the lines - line.remove(QRegExp(QStringLiteral("^msgid_plural\\s*\""))); - line.remove(_rxMsgLineRemEndQuote); - - _msgid.append(line); + } else if (part == Comment) { + if (!len && _obsolete) return OK; + if (!len) continue; + else if (line.startsWith(_obsoleteStart)) { + _comment += ('\n' + line); + _obsolete = true; + } else if (line.startsWith('#')) { + _comment += ('\n' + line); + } else if (line.startsWith(_msgctxtStart) && line.contains(_rxMsgCtxt)) { + part = Msgctxt; + + // remove quotes at beginning and the end of the lines + line.remove(QRegExp(QStringLiteral("^msgctxt\\s*\""))); + line.remove(_rxMsgLineRemEndQuote); + _msgctxt = line; + _msgctxtPresent = true; + //seenMsgctxt=true; + } else if (line.contains(_rxMsgId)) { + part = Msgid; + + // remove quotes at beginning and the end of the lines + line.remove(_rxMsgIdRemQuotes); + line.remove(_rxMsgLineRemEndQuote); + + _msgidMultiline = line.isEmpty(); + (*(_msgid).begin()) = line; } // one of the quotation marks is missing - else if(Q_UNLIKELY(/*_testBorked&&*/ line.contains( _rxMsgIdPluralBorked ) )) - { - part=Msgid; - _gettextPluralForm = true; - - // remove quotes at beginning and the end of the lines - line.remove(QRegExp(QStringLiteral("^msgid_plural\\s*\"?"))); - line.remove(_rxMsgLineRemEndQuote); - - _msgid.append(line); - - if(!line.isEmpty()) - recoverableError=true; - } - else if( !_gettextPluralForm && ( line.contains( _rxMsgStr ) ) ) - { - part=Msgstr; - - // remove quotes at beginning and the end of the lines - line.remove(_rxMsgStrRemQuotes); - line.remove(_rxMsgLineRemEndQuote); - - _msgstrMultiline=line.isEmpty(); - (*msgstrIt)=line; + else if (Q_UNLIKELY(/*_testBorked&&*/line.contains(_rxMsgIdBorked))) { + part = Msgid; + + // remove quotes at beginning and the end of the lines + line.remove(QRegExp("^msgid\\s*\"?")); + line.remove(_rxMsgLineRemEndQuote); + + _msgidMultiline = line.isEmpty(); + (*(_msgid).begin()) = line; + + if (!line.isEmpty()) + recoverableError = true; + } else { + qCDebug(LOKALIZE_LOG) << "no comment or msgid found after a comment while parsing: " << _comment; + error = true; + break; } - else if( !_gettextPluralForm && ( line.contains( _rxMsgStrOther )) ) - { - part=Msgstr; - - // remove quotes at beginning and the end of the lines - line.remove(_rxMsgStrRemQuotes); - line.remove(_rxMsgLineRemEndQuote); - - _msgstrMultiline=line.isEmpty(); - (*msgstrIt)=line; - - if(!line.isEmpty()) - recoverableError=true; + } else if (part == Msgctxt) { + if (!len) + continue; + else if (line.contains(_rxMsgLine)) { + // remove quotes at beginning and the end of the lines + line.remove(_rxMsgLineRemStartQuote); + line.remove(_rxMsgLineRemEndQuote); + + // add Msgctxt line to item + if (_msgctxt.isEmpty()) + _msgctxt = line; + else + _msgctxt += ('\n' + line); + _msgctxtPresent = true; + } else if (line.contains(_rxMsgId)) { + part = Msgid; + + // remove quotes at beginning and the end of the lines + line.remove(_rxMsgIdRemQuotes); + line.remove(_rxMsgLineRemEndQuote); + + _msgidMultiline = line.isEmpty(); + (*(_msgid).begin()) = line; } - else if( _gettextPluralForm && ( line.contains( _rxMsgStrPluralStart ) ) ) - { - part=Msgstr; - - // remove quotes at beginning and the end of the lines - line.remove(QRegExp(QStringLiteral("^msgstr\\[0\\]\\s*\"?"))); - line.remove(_rxMsgLineRemEndQuote); - - _msgstrMultiline=line.isEmpty(); - (*msgstrIt)=line; - } - else if(Q_UNLIKELY( /*_testBorked&&*/ _gettextPluralForm && line.contains( _rxMsgStrPluralStartBorked ) )) - { - part=Msgstr; - - // remove quotes at beginning and the end of the lines - line.remove(QRegExp(QStringLiteral("^msgstr\\[0\\]\\s*\"?"))); - line.remove(_rxMsgLineRemEndQuote); - - _msgstrMultiline=line.isEmpty(); - (*msgstrIt)=line; - - if(!line.isEmpty()) - recoverableError=true; + // one of the quotation marks is missing + else if (Q_UNLIKELY(/*_testBorked&&*/ line.contains(_rxMsgIdBorked))) { + part = Msgid; + + // remove quotes at beginning and the end of the lines + line.remove(QRegExp(QStringLiteral("^msgid\\s*\"?"))); + line.remove(_rxMsgLineRemEndQuote); + + _msgidMultiline = line.isEmpty(); + (*(_msgid).begin()) = line; + + if (!line.isEmpty()) + recoverableError = true; + } else { + qCDebug(LOKALIZE_LOG) << "no msgid found after a msgctxt while parsing: " << _msgctxt; + error = true; + break; } - else if ( line.startsWith( '#' ) ) - { - // ### TODO: could this be considered recoverable? - qCDebug(LOKALIZE_LOG) << "comment found after a msgid while parsing: " << _msgid.first(); - error=true; - break; + } else if (part == Msgid) { + if (!len) + continue; + else if (line.contains(_rxMsgLine)) { + // remove quotes at beginning and the end of the lines + line.remove(_rxMsgLineRemStartQuote); + line.remove(_rxMsgLineRemEndQuote); + + QStringList::Iterator it; + if (_gettextPluralForm) { + it = _msgid.end(); + --it; + } else + it = _msgid.begin(); + + // add Msgid line to item + if (it->isEmpty()) + (*it) = line; + else + (*it) += ('\n' + line); + } else if (line.contains(_rxMsgIdPlural)) { + part = Msgid; + _gettextPluralForm = true; + + // remove quotes at beginning and the end of the lines + line.remove(QRegExp(QStringLiteral("^msgid_plural\\s*\""))); + line.remove(_rxMsgLineRemEndQuote); + + _msgid.append(line); } - else if ( line.startsWith( QStringLiteral("msgid") ) ) - { - qCDebug(LOKALIZE_LOG) << "Another msgid found after a msgid while parsing: " << _msgid.first(); - error=true; - break; + // one of the quotation marks is missing + else if (Q_UNLIKELY(/*_testBorked&&*/ line.contains(_rxMsgIdPluralBorked))) { + part = Msgid; + _gettextPluralForm = true; + + // remove quotes at beginning and the end of the lines + line.remove(QRegExp(QStringLiteral("^msgid_plural\\s*\"?"))); + line.remove(_rxMsgLineRemEndQuote); + + _msgid.append(line); + + if (!line.isEmpty()) + recoverableError = true; + } else if (!_gettextPluralForm && (line.contains(_rxMsgStr))) { + part = Msgstr; + + // remove quotes at beginning and the end of the lines + line.remove(_rxMsgStrRemQuotes); + line.remove(_rxMsgLineRemEndQuote); + + _msgstrMultiline = line.isEmpty(); + (*msgstrIt) = line; + } else if (!_gettextPluralForm && (line.contains(_rxMsgStrOther))) { + part = Msgstr; + + // remove quotes at beginning and the end of the lines + line.remove(_rxMsgStrRemQuotes); + line.remove(_rxMsgLineRemEndQuote); + + _msgstrMultiline = line.isEmpty(); + (*msgstrIt) = line; + + if (!line.isEmpty()) + recoverableError = true; + } else if (_gettextPluralForm && (line.contains(_rxMsgStrPluralStart))) { + part = Msgstr; + + // remove quotes at beginning and the end of the lines + line.remove(QRegExp(QStringLiteral("^msgstr\\[0\\]\\s*\"?"))); + line.remove(_rxMsgLineRemEndQuote); + + _msgstrMultiline = line.isEmpty(); + (*msgstrIt) = line; + } else if (Q_UNLIKELY(/*_testBorked&&*/ _gettextPluralForm && line.contains(_rxMsgStrPluralStartBorked))) { + part = Msgstr; + + // remove quotes at beginning and the end of the lines + line.remove(QRegExp(QStringLiteral("^msgstr\\[0\\]\\s*\"?"))); + line.remove(_rxMsgLineRemEndQuote); + + _msgstrMultiline = line.isEmpty(); + (*msgstrIt) = line; + + if (!line.isEmpty()) + recoverableError = true; + } else if (line.startsWith('#')) { + // ### TODO: could this be considered recoverable? + qCDebug(LOKALIZE_LOG) << "comment found after a msgid while parsing: " << _msgid.first(); + error = true; + break; + } else if (line.startsWith(QStringLiteral("msgid"))) { + qCDebug(LOKALIZE_LOG) << "Another msgid found after a msgid while parsing: " << _msgid.first(); + error = true; + break; } // a line of the msgid with a missing quotation mark - else if(Q_UNLIKELY( /*_testBorked&&*/line.contains( _rxMsgLineBorked ) )) - { - recoverableError=true; - - // remove quotes at beginning and the end of the lines - line.remove(_rxMsgLineRemStartQuote); - line.remove(_rxMsgLineRemEndQuote); - - QStringList::Iterator it; - if( _gettextPluralForm ) - { - it=_msgid.end(); - --it; - } - else - it = _msgid.begin(); - - // add Msgid line to item - if(it->isEmpty()) - (*it)=line; - else - (*it)+=('\n'+line); + else if (Q_UNLIKELY(/*_testBorked&&*/line.contains(_rxMsgLineBorked))) { + recoverableError = true; + + // remove quotes at beginning and the end of the lines + line.remove(_rxMsgLineRemStartQuote); + line.remove(_rxMsgLineRemEndQuote); + + QStringList::Iterator it; + if (_gettextPluralForm) { + it = _msgid.end(); + --it; + } else + it = _msgid.begin(); + + // add Msgid line to item + if (it->isEmpty()) + (*it) = line; + else + (*it) += ('\n' + line); + } else { + qCDebug(LOKALIZE_LOG) << "no msgstr found after a msgid while parsing: " << _msgid.first(); + error = true; + break; } - else - { - qCDebug(LOKALIZE_LOG) << "no msgstr found after a msgid while parsing: " << _msgid.first(); - error=true; - break; - } - } - else if(part==Msgstr) - { - if(!len) - break; + } else if (part == Msgstr) { + if (!len) + break; // another line of the msgstr - else if( line.contains( _rxMsgLine ) ) - { - // remove quotes at beginning and the end of the lines - line.remove(_rxMsgLineRemStartQuote); - line.remove(_rxMsgLineRemEndQuote); - - if(!(*msgstrIt).isEmpty()) - (*msgstrIt)+='\n'; - (*msgstrIt)+=line; - } - else if( _gettextPluralForm && ( line.contains( _rxMsgStrPlural ) ) ) - { - // remove quotes at beginning and the end of the lines - line.remove(QRegExp(QStringLiteral("^msgstr\\[[0-9]+\\]\\s*\"?"))); - line.remove(_rxMsgLineRemEndQuote); - - _msgstr.append(line); - msgstrIt=_msgstr.end(); - --msgstrIt; - } - else if ( line.startsWith( '#' ) || line.startsWith( QStringLiteral("msgid") ) ) - { - _errorLine--; - _bufferedLine=line; - break; - } - else if(Q_UNLIKELY(/*_testBorked&&*/ _gettextPluralForm && ( line.contains( _rxMsgStrPluralBorked ) ) )) - { - // remove quotes at beginning and the end of the lines - line.remove(QRegExp(QStringLiteral("^msgstr\\[[0-9]\\]\\s*\"?"))); - line.remove(_rxMsgLineRemEndQuote); - - _msgstr.append(line); - msgstrIt=_msgstr.end(); - --msgstrIt; - - if(!line.isEmpty()) - recoverableError=true; - } - else if(line.startsWith(QLatin1String("msgstr"))) - { - qCDebug(LOKALIZE_LOG) << "Another msgstr found after a msgstr while parsing: " << line << _msgstr.last(); - error=true; - break; + else if (line.contains(_rxMsgLine)) { + // remove quotes at beginning and the end of the lines + line.remove(_rxMsgLineRemStartQuote); + line.remove(_rxMsgLineRemEndQuote); + + if (!(*msgstrIt).isEmpty()) + (*msgstrIt) += '\n'; + (*msgstrIt) += line; + } else if (_gettextPluralForm && (line.contains(_rxMsgStrPlural))) { + // remove quotes at beginning and the end of the lines + line.remove(QRegExp(QStringLiteral("^msgstr\\[[0-9]+\\]\\s*\"?"))); + line.remove(_rxMsgLineRemEndQuote); + + _msgstr.append(line); + msgstrIt = _msgstr.end(); + --msgstrIt; + } else if (line.startsWith('#') || line.startsWith(QStringLiteral("msgid"))) { + _errorLine--; + _bufferedLine = line; + break; + } else if (Q_UNLIKELY(/*_testBorked&&*/ _gettextPluralForm && (line.contains(_rxMsgStrPluralBorked)))) { + // remove quotes at beginning and the end of the lines + line.remove(QRegExp(QStringLiteral("^msgstr\\[[0-9]\\]\\s*\"?"))); + line.remove(_rxMsgLineRemEndQuote); + + _msgstr.append(line); + msgstrIt = _msgstr.end(); + --msgstrIt; + + if (!line.isEmpty()) + recoverableError = true; + } else if (line.startsWith(QLatin1String("msgstr"))) { + qCDebug(LOKALIZE_LOG) << "Another msgstr found after a msgstr while parsing: " << line << _msgstr.last(); + error = true; + break; } // another line of the msgstr with a missing quotation mark - else if(Q_UNLIKELY( /*_testBorked&&*/line.contains( _rxMsgLineBorked ) )) - { - recoverableError=true; - - // remove quotes at beginning and the end of the lines - line.remove(_rxMsgLineRemStartQuote); - line.remove(_rxMsgLineRemEndQuote); - - if(!(*msgstrIt).isEmpty()) - (*msgstrIt)+='\n'; - (*msgstrIt)+=line; - } - else - { - qCDebug(LOKALIZE_LOG) << "no msgid or comment found after a msgstr while parsing: " << _msgstr.last(); - error=true; - break; + else if (Q_UNLIKELY(/*_testBorked&&*/line.contains(_rxMsgLineBorked))) { + recoverableError = true; + + // remove quotes at beginning and the end of the lines + line.remove(_rxMsgLineRemStartQuote); + line.remove(_rxMsgLineRemEndQuote); + + if (!(*msgstrIt).isEmpty()) + (*msgstrIt) += '\n'; + (*msgstrIt) += line; + } else { + qCDebug(LOKALIZE_LOG) << "no msgid or comment found after a msgstr while parsing: " << _msgstr.last(); + error = true; + break; } } } -/* - if(_gettextPluralForm) - { - qCDebug(LOKALIZE_LOG) << "gettext plural form:\n" - << "msgid:\n" << _msgid.first() << "\n" - << "msgid_plural:\n" << _msgid.last() << "\n" << endl; - int counter=0; - for(QStringList::Iterator it = _msgstr.begin(); it != _msgstr.end(); ++it) + /* + if(_gettextPluralForm) { - qCDebug(LOKALIZE_LOG) << "msgstr[" << counter << "]:\n" - << (*it) << endl; - counter++; + qCDebug(LOKALIZE_LOG) << "gettext plural form:\n" + << "msgid:\n" << _msgid.first() << "\n" + << "msgid_plural:\n" << _msgid.last() << "\n" << endl; + int counter=0; + for(QStringList::Iterator it = _msgstr.begin(); it != _msgstr.end(); ++it) + { + qCDebug(LOKALIZE_LOG) << "msgstr[" << counter << "]:\n" + << (*it) << endl; + counter++; + } } - } - */ + */ //qCDebug(LOKALIZE_LOG) << " NEAR RETURN"; - if(Q_UNLIKELY(error)) + if (Q_UNLIKELY(error)) return PARSE_ERROR; - else if(Q_UNLIKELY(recoverableError)) + else if (Q_UNLIKELY(recoverableError)) return RECOVERED_PARSE_ERROR; else return OK; diff --git a/src/catalog/gettext/gettextstorage.h b/src/catalog/gettext/gettextstorage.h --- a/src/catalog/gettext/gettextstorage.h +++ b/src/catalog/gettext/gettextstorage.h @@ -6,7 +6,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved -by the membership of KDE e.V.), which shall act as a proxy +by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -30,8 +30,9 @@ /** * Implementation of Gettext PO format support */ -namespace GettextCatalog { - +namespace GettextCatalog +{ + /** * @short Implementation of storage for Gettext PO * @author Nick Shaforostoff @@ -42,29 +43,35 @@ GettextStorage(); ~GettextStorage(); - int capabilities() const{return 0;} + int capabilities() const + { + return 0; + } int load(QIODevice* device/*, bool readonly=false*/); - bool save(QIODevice* device, bool belongsToProject=false); + bool save(QIODevice* device, bool belongsToProject = false); int size() const; //flat-model interface (ignores XLIFF grouping) QString source(const DocPosition& pos) const; QString target(const DocPosition& pos) const; CatalogString sourceWithTags(DocPosition pos) const; CatalogString targetWithTags(DocPosition pos) const; - CatalogString catalogString(const DocPosition& pos) const{return pos.part==DocPosition::Target?targetWithTags(pos):sourceWithTags(pos);} + CatalogString catalogString(const DocPosition& pos) const + { + return pos.part == DocPosition::Target ? targetWithTags(pos) : sourceWithTags(pos); + } void targetDelete(const DocPosition& pos, int count); void targetInsert(const DocPosition& pos, const QString& arg); void setTarget(const DocPosition& pos, const QString& arg);//called for mergeCatalog void targetInsertTag(const DocPosition&, const InlineTag&); InlineTag targetDeleteTag(const DocPosition&); - QStringList sourceAllForms(const DocPosition& pos, bool stripNewLines=false) const; - QStringList targetAllForms(const DocPosition& pos, bool stripNewLines=false) const; + QStringList sourceAllForms(const DocPosition& pos, bool stripNewLines = false) const; + QStringList targetAllForms(const DocPosition& pos, bool stripNewLines = false) const; QVector notes(const DocPosition& pos) const; Note setNote(DocPosition pos, const Note& note); @@ -84,13 +91,25 @@ bool isEmpty(const DocPosition& pos) const; - QString mimetype()const{return QStringLiteral("text/x-gettext-translation");} - QString fileType()const{return QStringLiteral("Gettext (*.po)");} - CatalogType type()const{return Gettext;} + QString mimetype()const + { + return QStringLiteral("text/x-gettext-translation"); + } + QString fileType()const + { + return QStringLiteral("Gettext (*.po)"); + } + CatalogType type()const + { + return Gettext; + } private: bool setHeader(const CatalogItem& newHeader); - void setCodec(QTextCodec* codec) {m_codec = codec;} + void setCodec(QTextCodec* codec) + { + m_codec = codec; + } QVector notes(const DocPosition& pos, const QRegExp& re, int preLen) const; diff --git a/src/catalog/gettext/gettextstorage.cpp b/src/catalog/gettext/gettextstorage.cpp --- a/src/catalog/gettext/gettextstorage.cpp +++ b/src/catalog/gettext/gettextstorage.cpp @@ -49,11 +49,11 @@ using namespace GettextCatalog; GettextStorage::GettextStorage() - : CatalogStorage() - , m_codec(0) - , m_maxLineLength(80) - , m_trailingNewLines(0) - , m_generatedFromDocbook(false) + : CatalogStorage() + , m_codec(0) + , m_maxLineLength(80) + , m_trailingNewLines(0) + , m_generatedFromDocbook(false) { } @@ -72,60 +72,58 @@ int errorLine; { QMutexLocker locker(®ExMutex); - status = importer.open(device,this,&errorLine); + status = importer.open(device, this, &errorLine); } //for langs with more than 2 forms //we create any form-entries additionally needed - uint i=0; - uint lim=size(); - while (i msgstr(item.msgstrPlural()); - while (msgstr.count()m_catalogExtraData.join("\n\n").toUtf8(),9); - return status==OK?0:(errorLine+1); + return status == OK ? 0 : (errorLine + 1); } bool GettextStorage::save(QIODevice* device, bool belongsToProject) { - QString header=m_header.msgstr(); - QString comment=m_header.comment(); + QString header = m_header.msgstr(); + QString comment = m_header.comment(); QString catalogProjectId;//=m_url.fileName(); //catalogProjectId=catalogProjectId.left(catalogProjectId.lastIndexOf('.')); { QMutexLocker locker(®ExMutex); updateHeader(header, comment, - m_targetLangCode, - m_numberOfPluralForms, - catalogProjectId, - m_generatedFromDocbook, - belongsToProject, - /*forSaving*/true, - m_codec); + m_targetLangCode, + m_numberOfPluralForms, + catalogProjectId, + m_generatedFromDocbook, + belongsToProject, + /*forSaving*/true, + m_codec); } m_header.setMsgstr(header); m_header.setComment(comment); //GettextExportPlugin exporter(m_maxLineLength>70?m_maxLineLength:-1, m_trailingNewLines);// this is kinda hackish... GettextExportPlugin exporter(Project::instance()->wordWrap(), m_trailingNewLines); ConversionStatus status = OK; - status = exporter.save(device/*x-gettext-translation*/,this, m_codec); + status = exporter.save(device/*x-gettext-translation*/, this, m_codec); - return status==OK; + return status == OK; } //END OPEN/SAVE @@ -142,20 +140,19 @@ static InlineTag makeInlineTag(int i) { static const QString altSepText(QStringLiteral(" | ")); - static const QString ctype=i18n("separator for different-length string alternatives"); - return InlineTag(i,i,InlineTag::x,QString::number(i),QString(),altSepText,ctype); + static const QString ctype = i18n("separator for different-length string alternatives"); + return InlineTag(i, i, InlineTag::x, QString::number(i), QString(), altSepText, ctype); } static CatalogString makeCatalogString(const QString& string) { CatalogString result; - result.string=string; + result.string = string; - int i=0; + int i = 0; - while((i=result.string.indexOf(altSep, i))!=-1) - { - result.string[i]=TAGRANGE_IMAGE_SYMBOL; + while ((i = result.string.indexOf(altSep, i)) != -1) { + result.string[i] = TAGRANGE_IMAGE_SYMBOL; result.tags.append(makeInlineTag(i)); ++i; } @@ -191,19 +188,19 @@ } void GettextStorage::setTarget(const DocPosition& pos, const QString& arg) { - m_entries[pos.entry].d._msgstrPlural[pos.form]=arg; + m_entries[pos.entry].d._msgstrPlural[pos.form] = arg; } void GettextStorage::targetInsertTag(const DocPosition& pos, const InlineTag& tag) { Q_UNUSED(tag); - targetInsert(pos,altSep); + targetInsert(pos, altSep); } InlineTag GettextStorage::targetDeleteTag(const DocPosition& pos) { - targetDelete(pos,1); + targetDelete(pos, 1); return makeInlineTag(pos.offset); } @@ -220,61 +217,58 @@ QVector GettextStorage::altTrans(const DocPosition& pos) const { static const QRegExp alt_trans_mark_re(QStringLiteral("^#\\|")); - QStringList prev=m_entries.at(pos.entry).comment().split('\n').filter(alt_trans_mark_re); + QStringList prev = m_entries.at(pos.entry).comment().split('\n').filter(alt_trans_mark_re); QString oldSingular; QString oldPlural; - QString* cur=&oldSingular; - QStringList::iterator it=prev.begin(); - static const QString msgid_plural_alt=QStringLiteral("#| msgid_plural \""); - while (it!=prev.end()) - { + QString* cur = &oldSingular; + QStringList::iterator it = prev.begin(); + static const QString msgid_plural_alt = QStringLiteral("#| msgid_plural \""); + while (it != prev.end()) { if (it->startsWith(msgid_plural_alt)) - cur=&oldPlural; + cur = &oldPlural; - int start=it->indexOf('\"')+1; - int end=it->lastIndexOf('\"'); - if (start&&end!=-1) - { + int start = it->indexOf('\"') + 1; + int end = it->lastIndexOf('\"'); + if (start && end != -1) { if (!cur->isEmpty()) - (*cur)+='\n'; - if (!( cur->isEmpty() && (end-start)==0 ))//for multiline msgs - (*cur)+=it->midRef(start,end-start); + (*cur) += '\n'; + if (!(cur->isEmpty() && (end - start) == 0)) //for multiline msgs + (*cur) += it->midRef(start, end - start); } ++it; } - if (pos.form==0) - cur=&oldSingular; + if (pos.form == 0) + cur = &oldSingular; - cur->replace(QStringLiteral("\\\""),QStringLiteral("\"")); + cur->replace(QStringLiteral("\\\""), QStringLiteral("\"")); QVector result; if (!cur->isEmpty()) - result< l=notes(pos); - if (l.size()) oldNote=l.first(); + QVector l = notes(pos); + if (l.size()) oldNote = l.first(); - QStringList comment=m_entries.at(pos.entry).comment().split('\n'); + QStringList comment = m_entries.at(pos.entry).comment().split('\n'); //remove previous comment; - QStringList::iterator it=comment.begin(); - while (it!=comment.end()) - { + QStringList::iterator it = comment.begin(); + while (it != comment.end()) { if (it->startsWith(QLatin1String("# "))) - it=comment.erase(it); + it = comment.erase(it); else ++it; } if (note.content.size()) - comment.prepend(QStringLiteral("# ")+note.content.split('\n').join(QStringLiteral("\n# "))); + comment.prepend(QStringLiteral("# ") + note.content.split('\n').join(QStringLiteral("\n# "))); m_entries[pos.entry].setComment(comment.join(QStringLiteral("\n"))); //qCWarning(LOKALIZE_LOG)<<"e"< result; QString content; - QStringList note=m_entries.at(docPosition.entry).comment().split('\n').filter(re); + QStringList note = m_entries.at(docPosition.entry).comment().split('\n').filter(re); - foreach(const QString &s, note) - { - if (s.size()>=preLen) - { - content+=s.midRef(preLen); - content+=QLatin1Char('\n'); + foreach (const QString &s, note) { + if (s.size() >= preLen) { + content += s.midRef(preLen); + content += QLatin1Char('\n'); } } - if (!content.isEmpty()) - { + if (!content.isEmpty()) { content.chop(1); - result< GettextStorage::notes(const DocPosition& docPosition) const { static const QRegExp nre(QStringLiteral("^# ")); - return notes(docPosition,nre,2); + return notes(docPosition, nre, 2); } QVector GettextStorage::developerNotes(const DocPosition& docPosition) const { static const QRegExp dnre(QStringLiteral("^#\\. (?!i18n: file:)")); - return notes(docPosition,dnre,3); + return notes(docPosition, dnre, 3); } QStringList GettextStorage::sourceFiles(const DocPosition& pos) const { QStringList result; - QStringList commentLines=m_entries.at(pos.entry).comment().split('\n'); + QStringList commentLines = m_entries.at(pos.entry).comment().split('\n'); static const QRegExp i18n_file_re(QStringLiteral("^#. i18n: file: ")); - foreach(const QString &uiLine, commentLines.filter(i18n_file_re)) - { - foreach(const QStringRef &fileRef, uiLine.midRef(15).split(' ')) - { + foreach (const QString &uiLine, commentLines.filter(i18n_file_re)) { + foreach (const QStringRef &fileRef, uiLine.midRef(15).split(' ')) { result << fileRef.toString(); } } - bool hasUi=!result.isEmpty(); + bool hasUi = !result.isEmpty(); static const QRegExp cpp_re(QStringLiteral("^#: ")); - foreach(const QString &cppLine, commentLines.filter(cpp_re)) - { + foreach (const QString &cppLine, commentLines.filter(cpp_re)) { if (hasUi && cppLine.startsWith(QLatin1String("#: rc.cpp"))) continue; - foreach(const QStringRef &fileRef, cppLine.midRef(3).split(' ')) - { + foreach (const QStringRef &fileRef, cppLine.midRef(3).split(' ')) { result << fileRef.toString(); } } @@ -354,31 +341,31 @@ QStringList GettextStorage::matchData(const DocPosition& pos) const { - QString ctxt=m_entries.at(pos.entry).msgctxt(); + QString ctxt = m_entries.at(pos.entry).msgctxt(); //KDE-specific //Splits @info:whatsthis and actual note -/* if (ctxt.startsWith('@') && ctxt.contains(' ')) - { - QStringList result(ctxt.section(' ',0,0,QString::SectionSkipEmpty)); - result<poDir()); - - updateHeader(values, - comment, - m_targetLangCode, - m_numberOfPluralForms, - catalogProjectId, - m_generatedFromDocbook, - belongsToProject, - /*forSaving*/true, - m_codec); - m_header=newHeader; - m_header.setComment(comment); - m_header.setMsgstr(values); + QString comment = newHeader.comment(); + QString catalogProjectId;//=m_url.fileName(); FIXME m_url is always empty + //catalogProjectId=catalogProjectId.left(catalogProjectId.lastIndexOf('.')); + bool belongsToProject = m_url.contains(Project::instance()->poDir()); + + updateHeader(values, + comment, + m_targetLangCode, + m_numberOfPluralForms, + catalogProjectId, + m_generatedFromDocbook, + belongsToProject, + /*forSaving*/true, + m_codec); + m_header = newHeader; + m_header.setComment(comment); + m_header.setMsgstr(values); // setClean(false); - //emit signalHeaderChanged(); + //emit signalHeaderChanged(); - return true; - } - qCWarning(LOKALIZE_LOG) << "header Not valid"; - return false; + return true; + } + qCWarning(LOKALIZE_LOG) << "header Not valid"; + return false; } diff --git a/src/catalog/gettext/importplugin.cpp b/src/catalog/gettext/importplugin.cpp --- a/src/catalog/gettext/importplugin.cpp +++ b/src/catalog/gettext/importplugin.cpp @@ -45,7 +45,7 @@ #include -namespace GettextCatalog +namespace GettextCatalog { CatalogImportPlugin::CatalogImportPlugin() @@ -61,23 +61,23 @@ delete d; } -void CatalogImportPlugin::appendCatalogItem( const CatalogItem& item, const bool obsolete ) +void CatalogImportPlugin::appendCatalogItem(const CatalogItem& item, const bool obsolete) { if (item.msgid().isEmpty()) return; - if( obsolete ) + if (obsolete) d->_obsoleteEntries.append(item); else d->_entries.append(item); } -void CatalogImportPlugin::setCatalogExtraData( const QStringList& data ) +void CatalogImportPlugin::setCatalogExtraData(const QStringList& data) { - d->_catalogExtraData=data; - d->_updateCatalogExtraData=true; + d->_catalogExtraData = data; + d->_updateCatalogExtraData = true; } -void CatalogImportPlugin::setGeneratedFromDocbook( const bool generated ) +void CatalogImportPlugin::setGeneratedFromDocbook(const bool generated) { d->_generatedFromDocbook = generated; d->_updateGeneratedFromDocbook = true; @@ -89,28 +89,28 @@ d->_updateErrorList = true; } -void CatalogImportPlugin::setHeader( const CatalogItem& item ) +void CatalogImportPlugin::setHeader(const CatalogItem& item) { - d->_header=item; - d->_updateHeader=true; + d->_header = item; + d->_updateHeader = true; } -void CatalogImportPlugin::setCodec( QTextCodec* codec ) +void CatalogImportPlugin::setCodec(QTextCodec* codec) { d->_codec = codec; } ConversionStatus CatalogImportPlugin::open(QIODevice* device, GettextStorage* catalog, int* line) { - d->_catalog=catalog; + d->_catalog = catalog; startTransaction(); ConversionStatus result = load(device); - if( result == OK || result == RECOVERED_PARSE_ERROR || result == RECOVERED_HEADER_ERROR ) - commitTransaction(); + if (result == OK || result == RECOVERED_PARSE_ERROR || result == RECOVERED_HEADER_ERROR) + commitTransaction(); if (line) - (*line)=_errorLine; + (*line) = _errorLine; return result; } @@ -126,26 +126,26 @@ void CatalogImportPlugin::commitTransaction() { - GettextStorage* catalog=d->_catalog; + GettextStorage* catalog = d->_catalog; //catalog->clear(); // fill in the entries - QVector& entries=catalog->m_entries; - entries.reserve( d->_entries.count() ); //d->_catalog->setEntries( e ); - for( QLinkedList::const_iterator it = d->_entries.begin(); it != d->_entries.end(); ++it/*,++i*/ ) - entries.append( *it ); + QVector& entries = catalog->m_entries; + entries.reserve(d->_entries.count()); //d->_catalog->setEntries( e ); + for (QLinkedList::const_iterator it = d->_entries.begin(); it != d->_entries.end(); ++it/*,++i*/) + entries.append(*it); // The codec is specified in the header, so it must be updated before the header is. catalog->setCodec(d->_codec); - catalog->m_catalogExtraData=d->_catalogExtraData; - catalog->m_generatedFromDocbook=d->_generatedFromDocbook; + catalog->m_catalogExtraData = d->_catalogExtraData; + catalog->m_generatedFromDocbook = d->_generatedFromDocbook; catalog->setHeader(d->_header); //if( d->_updateErrorList ) d->_catalog->setErrorIndex(d->_errorList); - catalog->m_maxLineLength=_maxLineLength; - catalog->m_trailingNewLines=_trailingNewLines; + catalog->m_maxLineLength = _maxLineLength; + catalog->m_trailingNewLines = _trailingNewLines; } } diff --git a/src/catalog/gettext/importplugin_private.h b/src/catalog/gettext/importplugin_private.h --- a/src/catalog/gettext/importplugin_private.h +++ b/src/catalog/gettext/importplugin_private.h @@ -2,8 +2,8 @@ This file is part of Lokalize This file contains parts of KBabel code - Copyright (C) 2002-2003 by Stanislav Visnovsky - + Copyright (C) 2002-2003 by Stanislav Visnovsky + This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -41,7 +41,8 @@ #include class QTextCodec; -namespace GettextCatalog { +namespace GettextCatalog +{ class GettextStorage; class CatalogImportPluginPrivate diff --git a/src/catalog/gettextheader.h b/src/catalog/gettextheader.h --- a/src/catalog/gettextheader.h +++ b/src/catalog/gettextheader.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, diff --git a/src/catalog/gettextheader.cpp b/src/catalog/gettextheader.cpp --- a/src/catalog/gettextheader.cpp +++ b/src/catalog/gettextheader.cpp @@ -48,10 +48,9 @@ * on all languages KDE knows of **/ -struct langPInfo -{ - const char *lang; - const char *plural; +struct langPInfo { + const char *lang; + const char *plural; }; static const langPInfo langsWithPInfo[] = { @@ -126,53 +125,53 @@ { "zh_TW", "nplurals=1; plural=0;" } }; -static const size_t langsWithPInfoCount = sizeof (langsWithPInfo) / sizeof (langsWithPInfo[0]); +static const size_t langsWithPInfoCount = sizeof(langsWithPInfo) / sizeof(langsWithPInfo[0]); int numberOfPluralFormsFromHeader(const QString& header) { QRegExp rxplural(QStringLiteral("Plural-Forms:\\s*nplurals=(.);")); if (rxplural.indexIn(header) == -1) return 0; bool ok; - int result=rxplural.cap(1).toShort(&ok); - return ok?result:0; + int result = rxplural.cap(1).toShort(&ok); + return ok ? result : 0; } int numberOfPluralFormsForLangCode(const QString& langCode) { - QString expr=GNUPluralForms(langCode); + QString expr = GNUPluralForms(langCode); QRegExp rxplural(QStringLiteral("nplurals=(.);")); if (rxplural.indexIn(expr) == -1) return 0; bool ok; - int result=rxplural.cap(1).toShort(&ok); - return ok?result:0; + int result = rxplural.cap(1).toShort(&ok); + return ok ? result : 0; } QString GNUPluralForms(const QString& lang) { QByteArray l(lang.toUtf8()); - int i=langsWithPInfoCount; - while(--i>=0 && l!=langsWithPInfo[i].lang) + int i = langsWithPInfoCount; + while (--i >= 0 && l != langsWithPInfo[i].lang) ; - if (Q_LIKELY( i>=0 )) + if (Q_LIKELY(i >= 0)) return QString::fromLatin1(langsWithPInfo[i].plural); - i=langsWithPInfoCount; - while(--i>=0 && !l.startsWith(langsWithPInfo[i].lang)) + i = langsWithPInfoCount; + while (--i >= 0 && !l.startsWith(langsWithPInfo[i].lang)) ; - if (Q_LIKELY( i>=0 )) + if (Q_LIKELY(i >= 0)) return QString::fromLatin1(langsWithPInfo[i].plural); //BEGIN alternative // NOTE does this work under M$ OS? - qCWarning(LOKALIZE_LOG)<<"gonna call msginit"; - QString def=QStringLiteral("nplurals=2; plural=n != 1;"); + qCWarning(LOKALIZE_LOG) << "gonna call msginit"; + QString def = QStringLiteral("nplurals=2; plural=n != 1;"); QStringList arguments; arguments << QLatin1String("-l") << lang @@ -184,57 +183,53 @@ msginit.start(QLatin1String("msginit"), arguments); msginit.waitForStarted(5000); - if (Q_UNLIKELY( msginit.state()!=QProcess::Running )) - { + if (Q_UNLIKELY(msginit.state() != QProcess::Running)) { //qCWarning(LOKALIZE_LOG)<<"msginit error"; return def; } msginit.write( - "# SOME DESCRIPTIVE TITLE.\n" - "# Copyright (C) YEAR Free Software Foundation, Inc.\n" - "# FIRST AUTHOR , YEAR.\n" - "#\n" - "#, fuzzy\n" - "msgid \"\"\n" - "msgstr \"\"\n" - "\"Project-Id-Version: PACKAGE VERSION\\n\"\n" - "\"POT-Creation-Date: 2002-06-25 03:23+0200\\n\"\n" - "\"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n\"\n" - "\"Last-Translator: FULL NAME \\n\"\n" - "\"Language-Team: LANGUAGE \\n\"\n" - "\"Language: LL\\n\"\n" - "\"MIME-Version: 1.0\\n\"\n" - "\"Content-Type: text/plain; charset=UTF-8\\n\"\n" - "\"Content-Transfer-Encoding: ENCODING\\n\"\n" + "# SOME DESCRIPTIVE TITLE.\n" + "# Copyright (C) YEAR Free Software Foundation, Inc.\n" + "# FIRST AUTHOR , YEAR.\n" + "#\n" + "#, fuzzy\n" + "msgid \"\"\n" + "msgstr \"\"\n" + "\"Project-Id-Version: PACKAGE VERSION\\n\"\n" + "\"POT-Creation-Date: 2002-06-25 03:23+0200\\n\"\n" + "\"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n\"\n" + "\"Last-Translator: FULL NAME \\n\"\n" + "\"Language-Team: LANGUAGE \\n\"\n" + "\"Language: LL\\n\"\n" + "\"MIME-Version: 1.0\\n\"\n" + "\"Content-Type: text/plain; charset=UTF-8\\n\"\n" + "\"Content-Transfer-Encoding: ENCODING\\n\"\n" // "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n" - ); + ); msginit.closeWriteChannel(); - if (Q_UNLIKELY( !msginit.waitForFinished(5000) )) - { - qCWarning(LOKALIZE_LOG)<<"msginit error"; + if (Q_UNLIKELY(!msginit.waitForFinished(5000))) { + qCWarning(LOKALIZE_LOG) << "msginit error"; return def; } QByteArray result = msginit.readAll(); int pos = result.indexOf("Plural-Forms: "); - if (Q_UNLIKELY( pos==-1 )) - { + if (Q_UNLIKELY(pos == -1)) { //qCWarning(LOKALIZE_LOG)<<"msginit error"<'); - temp=QStringLiteral("Last-Translator: ") % authorNameEmail % BACKSLASH_N; + authorNameEmail += (QStringLiteral(" <") % Settings::authorEmail() % '>'); + temp = QStringLiteral("Last-Translator: ") % authorNameEmail % BACKSLASH_N; QRegExp lt(QStringLiteral("^ *Last-Translator:.*")); - for ( it = headerList.begin(),found=false; it != headerList.end() && !found; ++it ) - { - if (it->contains(lt)) - { + for (it = headerList.begin(), found = false; it != headerList.end() && !found; ++it) { + if (it->contains(lt)) { if (forSaving) *it = temp; - found=true; + found = true; } } - if (Q_UNLIKELY( !found )) + if (Q_UNLIKELY(!found)) headerList.append(temp); QLocale cLocale(QLocale::C); QString dateTimeString = cLocale.toString(QDateTime::currentDateTime(), QStringLiteral("yyyy-MM-dd hh:mm")); const int offset_seconds = QDateTime::currentDateTime().offsetFromUtc(); const int offset_hours = abs(offset_seconds) / 3600; const int offset_minutes = abs(offset_seconds % 3600) / 60; QString zoneOffsetString = (offset_seconds >= 0 ? '+' : '-') % (offset_hours < 10 ? QStringLiteral("0") : QStringLiteral("")) % QString::number(offset_hours) % (offset_minutes < 10 ? QStringLiteral("0") : QStringLiteral("")) % QString::number(offset_minutes); - temp=QStringLiteral("PO-Revision-Date: ") % dateTimeString % zoneOffsetString % BACKSLASH_N; + temp = QStringLiteral("PO-Revision-Date: ") % dateTimeString % zoneOffsetString % BACKSLASH_N; QRegExp poRevDate(QStringLiteral("^ *PO-Revision-Date:.*")); - for ( it = headerList.begin(),found=false; it != headerList.end() && !found; ++it ) - { - found=it->contains(poRevDate); + for (it = headerList.begin(), found = false; it != headerList.end() && !found; ++it) { + found = it->contains(poRevDate); if (found && forSaving) *it = temp; } - if (Q_UNLIKELY( !found )) + if (Q_UNLIKELY(!found)) headerList.append(temp); - temp=QStringLiteral("Project-Id-Version: ") % CatalogProjectId % BACKSLASH_N; + temp = QStringLiteral("Project-Id-Version: ") % CatalogProjectId % BACKSLASH_N; //temp.replace( "@PACKAGE@", packageName()); QRegExp projectIdVer(QStringLiteral("^ *Project-Id-Version:.*")); - for ( it = headerList.begin(),found=false; it != headerList.end() && !found; ++it ) - { - found=it->contains(projectIdVer); + for (it = headerList.begin(), found = false; it != headerList.end() && !found; ++it) { + found = it->contains(projectIdVer); if (found && it->contains(QLatin1String("PACKAGE VERSION"))) *it = temp; } - if (Q_UNLIKELY( !found )) + if (Q_UNLIKELY(!found)) headerList.append(temp); - langCode=Project::instance()->isLoaded()? - Project::instance()->langCode(): - Settings::defaultLangCode(); + langCode = Project::instance()->isLoaded() ? + Project::instance()->langCode() : + Settings::defaultLangCode(); QString language; //initialized with preexisting value or later QString mailingList; //initialized with preexisting value or later - static QMap langEnums; + static QMap langEnums; if (!langEnums.size()) - for (int l=QLocale::Abkhazian; l<=QLocale::Akoose; ++l) - langEnums[QLocale::languageToString((QLocale::Language)l)]=(QLocale::Language)l; - + for (int l = QLocale::Abkhazian; l <= QLocale::Akoose; ++l) + langEnums[QLocale::languageToString((QLocale::Language)l)] = (QLocale::Language)l; + static QRegExp langTeamRegExp(QStringLiteral("^ *Language-Team:.*")); - for ( it = headerList.begin(),found=false; it != headerList.end() && !found; ++it ) - { - found=it->contains(langTeamRegExp); - if (found) - { + for (it = headerList.begin(), found = false; it != headerList.end() && !found; ++it) { + found = it->contains(langTeamRegExp); + if (found) { //really parse header QRegExp re(QStringLiteral("^ *Language-Team: *(.*) *<([^>]*)>")); - if (re.indexIn(*it) != -1 ) - { - if (langEnums.contains( re.cap(1).trimmed() )) - { - language=re.cap(1).trimmed(); - mailingList=re.cap(2).trimmed(); + if (re.indexIn(*it) != -1) { + if (langEnums.contains(re.cap(1).trimmed())) { + language = re.cap(1).trimmed(); + mailingList = re.cap(2).trimmed(); QList locales = QLocale::matchingLocales(langEnums.value(language), QLocale::AnyScript, QLocale::AnyCountry); - if (locales.size()) langCode=locales.first().name().left(2); + if (locales.size()) langCode = locales.first().name().left(2); } } - ait=it; + ait = it; } } - if (language.isEmpty()) - { - language=QLocale::languageToString(QLocale(langCode).language()); + if (language.isEmpty()) { + language = QLocale::languageToString(QLocale(langCode).language()); if (language.isEmpty()) - language=langCode; + language = langCode; } - if (mailingList.isEmpty() || belongsToProject) - { + if (mailingList.isEmpty() || belongsToProject) { if (Project::instance()->isLoaded()) - mailingList=Project::instance()->mailingList(); + mailingList = Project::instance()->mailingList(); else //if (mailingList.isEmpty()) - mailingList=Settings::defaultMailingList(); + mailingList = Settings::defaultMailingList(); } - temp=QStringLiteral("Language-Team: ")%language%QStringLiteral(" <")%mailingList%QStringLiteral(">\\n"); - if (Q_LIKELY( found )) + temp = QStringLiteral("Language-Team: ") % language % QStringLiteral(" <") % mailingList % QStringLiteral(">\\n"); + if (Q_LIKELY(found)) (*ait) = temp; else headerList.append(temp); static QRegExp langCodeRegExp(QStringLiteral("^ *Language: *([^ \\\\]*)")); - temp=QStringLiteral("Language: ") % langCode % BACKSLASH_N; - for ( it = headerList.begin(),found=false; it != headerList.end() && !found; ++it ) - { - found=(langCodeRegExp.indexIn(*it)!=-1); + temp = QStringLiteral("Language: ") % langCode % BACKSLASH_N; + for (it = headerList.begin(), found = false; it != headerList.end() && !found; ++it) { + found = (langCodeRegExp.indexIn(*it) != -1); if (found && langCodeRegExp.cap(1).isEmpty()) - *it=temp; + *it = temp; //if (found) qCWarning(LOKALIZE_LOG)<<"got explicit lang code:"<contains(ctRe); - if (found) *it=temp; + for (it = headerList.begin(), found = false; it != headerList.end() && !found; ++it) { + found = it->contains(ctRe); + if (found) *it = temp; } - if (Q_UNLIKELY( !found )) + if (Q_UNLIKELY(!found)) headerList.append(temp); - temp=QStringLiteral("Content-Transfer-Encoding: 8bit\\n"); + temp = QStringLiteral("Content-Transfer-Encoding: 8bit\\n"); QRegExp cteRe(QStringLiteral("^ *Content-Transfer-Encoding:.*")); - for ( it = headerList.begin(),found=false; it != headerList.end() && !found; ++it ) - found=it->contains(cteRe); + for (it = headerList.begin(), found = false; it != headerList.end() && !found; ++it) + found = it->contains(cteRe); if (!found) headerList.append(temp); // ensure MIME-Version header - temp=QStringLiteral("MIME-Version: 1.0\\n"); + temp = QStringLiteral("MIME-Version: 1.0\\n"); QRegExp mvRe(QStringLiteral("^ *MIME-Version:")); - for ( it = headerList.begin(),found=false; it != headerList.end()&& !found; ++it ) - { - found=it->contains(mvRe); + for (it = headerList.begin(), found = false; it != headerList.end() && !found; ++it) { + found = it->contains(mvRe); if (found) *it = temp; } - if (Q_UNLIKELY( !found )) + if (Q_UNLIKELY(!found)) headerList.append(temp); //qCDebug(LOKALIZE_LOG)<<"testing for GNUPluralForms"; // update plural form header QRegExp pfRe(QStringLiteral("^ *Plural-Forms:")); - for ( it = headerList.begin(),found=false; it != headerList.end()&& !found; ++it ) - found=it->contains(pfRe); - if (found) - { + for (it = headerList.begin(), found = false; it != headerList.end() && !found; ++it) + found = it->contains(pfRe); + if (found) { --it; //qCDebug(LOKALIZE_LOG)<<"GNUPluralForms found"; - int num=numberOfPluralFormsFromHeader(header); - if (!num) - { + int num = numberOfPluralFormsFromHeader(header); + if (!num) { if (generatedFromDocbook) - num=1; - else - { - qCWarning(LOKALIZE_LOG)<<"No plural form info in header, using project-defined one"<replace(pf,temp); - num=numberOfPluralFormsFromHeader(temp); - } - else - { - qCWarning(LOKALIZE_LOG)<<"no... smth went wrong :(\ncheck your gettext install"; - num=2; + temp = QStringLiteral("Plural-Forms: %1\\n").arg(t); + it->replace(pf, temp); + num = numberOfPluralFormsFromHeader(temp); + } else { + qCWarning(LOKALIZE_LOG) << "no... smth went wrong :(\ncheck your gettext install"; + num = 2; } } } - numberOfPluralForms=num; + numberOfPluralForms = num; - } - else if ( !generatedFromDocbook) - { + } else if (!generatedFromDocbook) { //qCDebug(LOKALIZE_LOG)<<"generating GNUPluralForms"<contains(xgRe); + for (it = headerList.begin(), found = false; it != headerList.end() && !found; ++it) { + found = it->contains(xgRe); if (found) *it = temp; } - if (Q_UNLIKELY( !found )) + if (Q_UNLIKELY(!found)) headerList.append(temp); //m_header.setMsgstr( headerList.join( "\n" ) ); - header=headerList.join(QStringLiteral("\n")); + header = headerList.join(QStringLiteral("\n")); //END header itself //BEGIN comment = description, copyrights // U+00A9 is the Copyright sign QRegExp fsfc(QStringLiteral("^# *Copyright (\\(C\\)|\\x00a9).*Free Software Foundation, Inc")); - for ( it = commentList.begin(),found=false; it != commentList.end()&&!found; ++it ) - { - found=it->contains( fsfc ) ; + for (it = commentList.begin(), found = false; it != commentList.end() && !found; ++it) { + found = it->contains(fsfc) ; if (found) it->replace(QStringLiteral("YEAR"), cLocale.toString(QDate::currentDate(), QStringLiteral("yyyy"))); } -/* - if( saveOptions.FSFCopyright == ProjectSettingsBase::Update ) - { - //update years - QString cy = cLocale.toString(QDate::currentDate(), "yyyy"); - if( !it->contains( QRegExp(cy)) ) // is the year already included? - { - int index = it->lastIndexOf( QRegExp("[\\d]+[\\d\\-, ]*") ); - if( index == -1 ) - { - KMessageBox::information(0,i18n("Free Software Foundation Copyright does not contain any year. " - "It will not be updated.")); - } else { - it->insert(index+1, QString(", ")+cy); - } - } - }*/ + /* + if( saveOptions.FSFCopyright == ProjectSettingsBase::Update ) + { + //update years + QString cy = cLocale.toString(QDate::currentDate(), "yyyy"); + if( !it->contains( QRegExp(cy)) ) // is the year already included? + { + int index = it->lastIndexOf( QRegExp("[\\d]+[\\d\\-, ]*") ); + if( index == -1 ) + { + KMessageBox::information(0,i18n("Free Software Foundation Copyright does not contain any year. " + "It will not be updated.")); + } else { + it->insert(index+1, QString(", ")+cy); + } + } + }*/ #if 0 - if ( ( !usePrefs || saveOptions.updateDescription ) - && ( !saveOptions.descriptionString.isEmpty() ) ) - { - temp = "# "+saveOptions.descriptionString; - temp.replace( "@PACKAGE@", packageName()); - temp.replace( "@LANGUAGE@", identityOptions.languageName); + if ((!usePrefs || saveOptions.updateDescription) + && (!saveOptions.descriptionString.isEmpty())) { + temp = "# " + saveOptions.descriptionString; + temp.replace("@PACKAGE@", packageName()); + temp.replace("@LANGUAGE@", identityOptions.languageName); temp = temp.trimmed(); // The description strings has often buggy variants already in the file, these must be removed - QString regexpstr = "^#\\s+" + QRegExp::escape( saveOptions.descriptionString.trimmed() ) + "\\s*$"; - regexpstr.replace( "@PACKAGE@", ".*" ); - regexpstr.replace( "@LANGUAGE@", ".*" ); + QString regexpstr = "^#\\s+" + QRegExp::escape(saveOptions.descriptionString.trimmed()) + "\\s*$"; + regexpstr.replace("@PACKAGE@", ".*"); + regexpstr.replace("@LANGUAGE@", ".*"); //qCDebug(LOKALIZE_LOG) << "REGEXPSTR: " << regexpstr; - QRegExp regexp ( regexpstr ); + QRegExp regexp(regexpstr); // The buggy variants exist in English too (of a time before KBabel got a translation for the corresponding language) - QRegExp regexpUntranslated ( "^#\\s+translation of .* to .*\\s*$" ); + QRegExp regexpUntranslated("^#\\s+translation of .* to .*\\s*$"); qCDebug(LOKALIZE_LOG) << "Temp is '" << temp << "'"; - found=false; - bool foundTemplate=false; + found = false; + bool foundTemplate = false; it = commentList.begin(); - while ( it != commentList.end() ) - { + while (it != commentList.end()) { qCDebug(LOKALIZE_LOG) << "testing '" << (*it) << "'"; bool deleteItem = false; - if ( (*it) == temp ) - { + if ((*it) == temp) { qCDebug(LOKALIZE_LOG) << "Match "; - if ( found ) + if (found) deleteItem = true; else - found=true; - } - else if ( regexp.indexIn( *it ) >= 0 ) - { + found = true; + } else if (regexp.indexIn(*it) >= 0) { // We have a similar (translated) string (from another project or another language (perhaps typos)). Remove it. deleteItem = true; - } - else if ( regexpUntranslated.indexIn( *it ) >= 0 ) - { + } else if (regexpUntranslated.indexIn(*it) >= 0) { // We have a similar (untranslated) string (from another project or another language (perhaps typos)). Remove it. deleteItem = true; - } - else if ( (*it) == "# SOME DESCRIPTIVE TITLE." ) - { + } else if ((*it) == "# SOME DESCRIPTIVE TITLE.") { // We have the standard title placeholder, remove it deleteItem = true; } - if ( deleteItem ) - it = commentList.erase( it ); + if (deleteItem) + it = commentList.erase(it); else ++it; } @@ -594,107 +550,89 @@ // return; QStringList foundAuthors; - temp=QStringLiteral("# ")%authorNameEmail%QStringLiteral(", ")%cLocale.toString(QDate::currentDate(), QStringLiteral("yyyy"))%'.'; + temp = QStringLiteral("# ") % authorNameEmail % QStringLiteral(", ") % cLocale.toString(QDate::currentDate(), QStringLiteral("yyyy")) % '.'; // ### TODO: it would be nice if the entry could start with "COPYRIGHT" and have the "(C)" symbol (both not mandatory) - QRegExp regexpAuthorYear( QStringLiteral("^#.*(<.+@.+>)?,\\s*([\\d]+[\\d\\-, ]*|YEAR)") ); - QRegExp regexpYearAlone( QStringLiteral("^# , \\d{4}.?\\s*$") ); - if (commentList.isEmpty()) - { + QRegExp regexpAuthorYear(QStringLiteral("^#.*(<.+@.+>)?,\\s*([\\d]+[\\d\\-, ]*|YEAR)")); + QRegExp regexpYearAlone(QStringLiteral("^# , \\d{4}.?\\s*$")); + if (commentList.isEmpty()) { commentList.append(temp); commentList.append(QString()); - } - else - { + } else { it = commentList.begin(); - while ( it != commentList.end() ) - { + while (it != commentList.end()) { bool deleteItem = false; - if ( it->indexOf( QLatin1String("copyright"), 0, Qt::CaseInsensitive ) != -1 ) - { + if (it->indexOf(QLatin1String("copyright"), 0, Qt::CaseInsensitive) != -1) { // We have a line with a copyright. It should not be moved. - } - else if ( it->contains( QRegExp(QStringLiteral("#, *fuzzy")) ) ) + } else if (it->contains(QRegExp(QStringLiteral("#, *fuzzy")))) deleteItem = true; - else if ( it->contains( regexpYearAlone ) ) - { + else if (it->contains(regexpYearAlone)) { // We have found a year number that is preceded by a comma. // That is typical of KBabel 1.10 (and earlier?) when there is neither an author name nor an email // Remove the entry deleteItem = true; - } - else if ( it->contains( QLatin1String("# FIRST AUTHOR , YEAR.")) ) + } else if (it->contains(QLatin1String("# FIRST AUTHOR , YEAR."))) deleteItem = true; - else if ( it->contains( QLatin1String("# SOME DESCRIPTIVE TITLE"))) + else if (it->contains(QLatin1String("# SOME DESCRIPTIVE TITLE"))) deleteItem = true; - else if ( it->contains( regexpAuthorYear ) ) // email address followed by year - { - if ( !foundAuthors.contains( (*it) ) ) - { + else if (it->contains(regexpAuthorYear)) { // email address followed by year + if (!foundAuthors.contains((*it))) { // The author line is new (and not a duplicate), so add it to the author line list - foundAuthors.append( (*it) ); + foundAuthors.append((*it)); } // Delete also non-duplicated entry, as now all what is needed will be processed in foundAuthors deleteItem = true; } - if ( deleteItem ) - it = commentList.erase( it ); + if (deleteItem) + it = commentList.erase(it); else ++it; } - if ( !foundAuthors.isEmpty() ) - { + if (!foundAuthors.isEmpty()) { found = false; bool foundAuthor = false; const QString cy = cLocale.toString(QDate::currentDate(), QStringLiteral("yyyy")); ait = foundAuthors.end(); - for ( it = foundAuthors.begin() ; it!=foundAuthors.end(); ++it ) - { - if ( it->contains(Settings::authorName()) || it->contains(Settings::authorEmail()) ) - { + for (it = foundAuthors.begin() ; it != foundAuthors.end(); ++it) { + if (it->contains(Settings::authorName()) || it->contains(Settings::authorEmail())) { foundAuthor = true; - if ( it->contains( cy ) ) + if (it->contains(cy)) found = true; else ait = it; } } - if ( !found ) - { - if ( !foundAuthor ) + if (!found) { + if (!foundAuthor) foundAuthors.append(temp); - else if ( ait != foundAuthors.end() ) - { + else if (ait != foundAuthors.end()) { //update years - const int index = (*ait).lastIndexOf( QRegExp(QStringLiteral("[\\d]+[\\d\\-, ]*")) ); - if ( index == -1 ) - (*ait)+=QStringLiteral(", ")%cy; + const int index = (*ait).lastIndexOf(QRegExp(QStringLiteral("[\\d]+[\\d\\-, ]*"))); + if (index == -1) + (*ait) += QStringLiteral(", ") % cy; else - ait->insert(index+1, QStringLiteral(", ")%cy); - } - else + ait->insert(index + 1, QStringLiteral(", ") % cy); + } else qCDebug(LOKALIZE_LOG) << "INTERNAL ERROR: author found but iterator dangling!"; } - } - else + } else foundAuthors.append(temp); - foreach (QString author, foundAuthors) - { + foreach (QString author, foundAuthors) { // ensure dot at the end of copyright - if ( !author.endsWith(QLatin1Char('.')) ) author += QLatin1Char('.'); + if (!author.endsWith(QLatin1Char('.'))) author += QLatin1Char('.'); commentList.append(author); } } //m_header.setComment( commentList.join( "\n" ) ); - comment=commentList.join(QStringLiteral("\n")); + comment = commentList.join(QStringLiteral("\n")); //END comment = description, copyrights } @@ -705,34 +643,30 @@ bool askAuthorInfoIfEmpty() { - if(QThread::currentThread() == qApp->thread()) - { + if (QThread::currentThread() == qApp->thread()) { - if (Settings::authorName().isEmpty()) - { + if (Settings::authorName().isEmpty()) { bool ok; QString contact = QInputDialog::getText( - SettingsController::instance()->mainWindowPtr(), - i18nc("@window:title", "Author name missing"), i18n("Your name:"), - QLineEdit::Normal, fullUserName(), &ok); + SettingsController::instance()->mainWindowPtr(), + i18nc("@window:title", "Author name missing"), i18n("Your name:"), + QLineEdit::Normal, fullUserName(), &ok); #ifndef NOKDE - Settings::self()->authorNameItem()->setValue(ok?contact:fullUserName()); + Settings::self()->authorNameItem()->setValue(ok ? contact : fullUserName()); Settings::self()->save(); #else - Settings::self()->setAuthorName(ok?contact:fullUserName()); + Settings::self()->setAuthorName(ok ? contact : fullUserName()); #endif } - if (Settings::authorEmail().isEmpty()) - { + if (Settings::authorEmail().isEmpty()) { bool ok; QString email = QInputDialog::getText( - SettingsController::instance()->mainWindowPtr(), - i18nc("@window:title", "Author email missing"), i18n("Your email:"), - QLineEdit::Normal, QString(), &ok); + SettingsController::instance()->mainWindowPtr(), + i18nc("@window:title", "Author email missing"), i18n("Your email:"), + QLineEdit::Normal, QString(), &ok); - if (ok) - { + if (ok) { #ifndef NOKDE Settings::self()->authorEmailItem()->setValue(email); Settings::self()->save(); diff --git a/src/catalog/note.h b/src/catalog/note.h --- a/src/catalog/note.h +++ b/src/catalog/note.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -26,33 +26,32 @@ #include -struct Note -{ - enum Owner{General,Source,Target}; +struct Note { + enum Owner {General, Source, Target}; QString content; char priority;//1 is the highest Owner annotates; QString from; QString lang; - Note(const QString& content_=QString()) + Note(const QString& content_ = QString()) : content(content_) , priority(5) , annotates(General) - {} + {} - Note(const QString& content_,char priority_,Owner annotates_,const QString& from_,const QString& lang_) + Note(const QString& content_, char priority_, Owner annotates_, const QString& from_, const QString& lang_) : content(content_) , priority(priority_) , annotates(annotates_) , from(from_) , lang(lang_) - {} + {} bool operator<(const Note& other) const { - return priority class Catalog; -struct Phase -{ +struct Phase { QString name; QString process; QString company; @@ -57,24 +56,23 @@ bool operator<(const Phase& other) const { - return date=0 && !process.startsWith(processes()[--i])) + int i = ProjectLocal::Undefined; + while (i >= 0 && !process.startsWith(processes()[--i])) ; - return (i==-1)?Project::local()->role():ProjectLocal::PersonRole(i); + return (i == -1) ? Project::local()->role() : ProjectLocal::PersonRole(i); } void generatePhaseForCatalogIfNeeded(Catalog* catalog) { - if (Q_LIKELY( !(catalog->capabilities()&Phases) || catalog->activePhaseRole()==ProjectLocal::Undefined )) + if (Q_LIKELY(!(catalog->capabilities()&Phases) || catalog->activePhaseRole() == ProjectLocal::Undefined)) return; Phase phase; - phase.process=processes()[Project::local()->role()]; + phase.process = processes()[Project::local()->role()]; if (initPhaseForCatalog(catalog, phase)) static_cast(catalog)->push(new UpdatePhaseCmd(catalog, phase)); @@ -65,28 +65,25 @@ { askAuthorInfoIfEmpty(); - phase.contact=Settings::authorName(); + phase.contact = Settings::authorName(); QSet names; - QList phases=catalog->allPhases(); + QList phases = catalog->allPhases(); qSort(phases.begin(), phases.end(), qGreater()); - foreach (const Phase& p, phases) - { - if (!(options&ForceAdd) && p.contact==phase.contact && p.process==phase.process) - { - phase=p; + foreach (const Phase& p, phases) { + if (!(options & ForceAdd) && p.contact == phase.contact && p.process == phase.process) { + phase = p; break; } names.insert(p.name); } - if (phase.name.isEmpty()) - { - int i=0; - while (names.contains(phase.name=phase.process+QStringLiteral("-%1").arg(++i))) + if (phase.name.isEmpty()) { + int i = 0; + while (names.contains(phase.name = phase.process + QStringLiteral("-%1").arg(++i))) ; - phase.date=QDate::currentDate(); - phase.email=Settings::authorEmail(); + phase.date = QDate::currentDate(); + phase.email = Settings::authorEmail(); return true; } return false; diff --git a/src/catalog/pos.h b/src/catalog/pos.h --- a/src/catalog/pos.h +++ b/src/catalog/pos.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -35,74 +35,79 @@ * * @short Structure that represents a position in a catalog */ -struct DocPosition -{ - enum Part - { - UndefPart=0, - Source=1, - Target=2, - Comment=4 +struct DocPosition { + enum Part { + UndefPart = 0, + Source = 1, + Target = 2, + Comment = 4 }; - int entry:32; - Part part:8; - char form:8; - uint offset:16; + int entry: 32; + Part part: 8; + char form: 8; + uint offset: 16; - DocPosition(): entry(-1),part(Target),form(0),offset(0){} + DocPosition(): entry(-1), part(Target), form(0), offset(0) {} - DocPosition(int entry_, Part part_, char form_=0, uint offset_=0) + DocPosition(int entry_, Part part_, char form_ = 0, uint offset_ = 0) : entry(entry_) , part(part_) , form(form_) , offset(offset_) - {} + {} - DocPosition(int entry_, char form_=0, uint offset_=0) + DocPosition(int entry_, char form_ = 0, uint offset_ = 0) : entry(entry_) , part(Target) , form(form_) , offset(offset_) - {} + {} bool operator==(const DocPosition& pos) const - {return entry==pos.entry && form==pos.form;}; + { + return entry == pos.entry && form == pos.form; + }; }; Q_DECLARE_METATYPE(DocPosition) -bool switchPrev(Catalog*&,DocPosition& pos,int parts=DocPosition::Target); -bool switchNext(Catalog*&,DocPosition& pos,int parts=DocPosition::Target); +bool switchPrev(Catalog*&, DocPosition& pos, int parts = DocPosition::Target); +bool switchNext(Catalog*&, DocPosition& pos, int parts = DocPosition::Target); /** * simpler version of DocPosition for use in QMap */ -struct DocPos -{ - int entry:24; - uchar form:8; +struct DocPos { + int entry: 24; + uchar form: 8; - DocPos():entry(-1), form(0){} + DocPos(): entry(-1), form(0) {} DocPos(int _entry, uchar _form): entry(_entry), form(_form) - {} + {} DocPos(const DocPosition& pos): entry(pos.entry), form(pos.form) - {} + {} bool operator<(const DocPos& pos) const - {return entry==pos.entry?form0 - && catalog->isPlural(pos.entry))) + if (Q_UNLIKELY(pos.form > 0 + && catalog->isPlural(pos.entry))) pos.form--; - else if (Q_UNLIKELY( pos.entry==0 )) + else if (Q_UNLIKELY(pos.entry == 0)) return false; - else - { + else { pos.entry--; - pos.form=catalog->isPlural(pos.entry)*(catalog->numberOfPluralForms()-1); + pos.form = catalog->isPlural(pos.entry) * (catalog->numberOfPluralForms() - 1); } - pos.offset=0; + pos.offset = 0; - if (parts&DocPosition::Comment && !skipCommentThisTime && pos.form==0 && catalog->notes(pos).size()) - { - pos.part=DocPosition::Comment; - pos.form=catalog->notes(pos).size()-1; - } - else - pos.part=DocPosition::Target; + if (parts & DocPosition::Comment && !skipCommentThisTime && pos.form == 0 && catalog->notes(pos).size()) { + pos.part = DocPosition::Comment; + pos.form = catalog->notes(pos).size() - 1; + } else + pos.part = DocPosition::Target; return true; } -bool switchNext(Catalog*& catalog,DocPosition& pos,int parts) +bool switchNext(Catalog*& catalog, DocPosition& pos, int parts) { - bool switchEntry=false; - bool switchCommentIndex=false; - if (pos.part==DocPosition::Source) - pos.part=DocPosition::Target; - else if (pos.part==DocPosition::Target) - { - if (parts&DocPosition::Comment && pos.form==0 && catalog->notes(pos).size()) - pos.part=DocPosition::Comment; + bool switchEntry = false; + bool switchCommentIndex = false; + if (pos.part == DocPosition::Source) + pos.part = DocPosition::Target; + else if (pos.part == DocPosition::Target) { + if (parts & DocPosition::Comment && pos.form == 0 && catalog->notes(pos).size()) + pos.part = DocPosition::Comment; else - switchEntry=true; - } - else if (pos.part==DocPosition::Comment) - switchCommentIndex=true; + switchEntry = true; + } else if (pos.part == DocPosition::Comment) + switchCommentIndex = true; - if (switchCommentIndex) - { + if (switchCommentIndex) { pos.form++; - if (catalog->notes(pos).size()==pos.form) - { - pos.form=0; - switchEntry=true; + if (catalog->notes(pos).size() == pos.form) { + pos.form = 0; + switchEntry = true; } } if (!switchEntry) return true; - if (Q_UNLIKELY( pos.entry!=-1 - && pos.form+1 < catalog->numberOfPluralForms() - && catalog->isPlural(pos.entry))) + if (Q_UNLIKELY(pos.entry != -1 + && pos.form + 1 < catalog->numberOfPluralForms() + && catalog->isPlural(pos.entry))) pos.form++; - else if (Q_UNLIKELY( pos.entry==catalog->numberOfEntries()-1 )) + else if (Q_UNLIKELY(pos.entry == catalog->numberOfEntries() - 1)) return false; - else - { + else { pos.entry++; - pos.form=0; + pos.form = 0; } - pos.offset=0; + pos.offset = 0; - pos.part=(parts&DocPosition::Source)?DocPosition::Source:DocPosition::Target; + pos.part = (parts & DocPosition::Source) ? DocPosition::Source : DocPosition::Target; return true; } @@ -143,18 +132,18 @@ argument >> entry >> form >> offset; argument.endStructure(); - pos.entry=entry; - pos.form=form; - pos.offset=offset; + pos.entry = entry; + pos.form = form; + pos.offset = offset; return argument; } QDBusArgument &operator<<(QDBusArgument &argument, const DocPosition &pos) { - int entry=pos.entry; - int form=pos.form; - uint offset=pos.offset; + int entry = pos.entry; + int form = pos.form; + uint offset = pos.offset; argument.beginStructure(); argument << entry << form << offset; diff --git a/src/catalog/state.h b/src/catalog/state.h --- a/src/catalog/state.h +++ b/src/catalog/state.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -25,8 +25,7 @@ #define STATE_H ///@see @link http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#state -enum TargetState -{ +enum TargetState { New, NeedsTranslation, NeedsL10n, diff --git a/src/catalog/ts/tsstorage.h b/src/catalog/ts/tsstorage.h --- a/src/catalog/ts/tsstorage.h +++ b/src/catalog/ts/tsstorage.h @@ -38,7 +38,7 @@ int capabilities() const; int load(QIODevice* device); - bool save(QIODevice* device, bool belongsToProject=false); + bool save(QIODevice* device, bool belongsToProject = false); int size() const; bool isEmpty() const; @@ -51,8 +51,14 @@ CatalogString catalogString(const DocPosition& pos) const; /// all plural forms. pos.form doesn't matter TODO - QStringList sourceAllForms(const DocPosition& pos, bool stripNewLines=false) const{Q_UNUSED(pos) Q_UNUSED(stripNewLines) return QStringList();} - QStringList targetAllForms(const DocPosition& pos, bool stripNewLines=false) const{Q_UNUSED(pos) Q_UNUSED(stripNewLines) return QStringList();} + QStringList sourceAllForms(const DocPosition& pos, bool stripNewLines = false) const + { + Q_UNUSED(pos) Q_UNUSED(stripNewLines) return QStringList(); + } + QStringList targetAllForms(const DocPosition& pos, bool stripNewLines = false) const + { + Q_UNUSED(pos) Q_UNUSED(stripNewLines) return QStringList(); + } void targetDelete(const DocPosition& pos, int count); void targetInsert(const DocPosition& pos, const QString& arg); @@ -82,9 +88,18 @@ bool isObsolete(int entry) const; - QString mimetype()const{return QStringLiteral("application/x-linguist");} - QString fileType()const{return QStringLiteral("Qt Linguist (*.ts)");} - CatalogType type()const{return Ts;} + QString mimetype()const + { + return QStringLiteral("application/x-linguist"); + } + QString fileType()const + { + return QStringLiteral("Qt Linguist (*.ts)"); + } + CatalogType type()const + { + return Ts; + } void setTargetLangCode(const QString& langCode); diff --git a/src/catalog/ts/tsstorage.cpp b/src/catalog/ts/tsstorage.cpp --- a/src/catalog/ts/tsstorage.cpp +++ b/src/catalog/ts/tsstorage.cpp @@ -46,17 +46,17 @@ //static const char* const noyes[]={"no","yes"}; -static const QString names[]={U("source"),U("translation"),U("oldsource"),U("translatorcomment"),U("comment"),U("name"),U("numerus")}; -enum TagNames {SourceTag ,TargetTag ,OldSourceTag ,NoteTag ,DevNoteTag ,NameTag ,PluralTag}; +static const QString names[] = {U("source"), U("translation"), U("oldsource"), U("translatorcomment"), U("comment"), U("name"), U("numerus")}; +enum TagNames {SourceTag, TargetTag, OldSourceTag, NoteTag, DevNoteTag, NameTag, PluralTag}; -static const QString attrnames[]={U("location"),U("type"),U("obsolete")}; -enum AttrNames {LocationAttr ,TypeAttr ,ObsoleteAttr}; +static const QString attrnames[] = {U("location"), U("type"), U("obsolete")}; +enum AttrNames {LocationAttr, TypeAttr, ObsoleteAttr}; -static const QString attrvalues[]={U("obsolete"),U("vanished")}; -enum AttValues {ObsoleteVal ,VanishedVal}; +static const QString attrvalues[] = {U("obsolete"), U("vanished")}; +enum AttValues {ObsoleteVal, VanishedVal}; TsStorage::TsStorage() - : CatalogStorage() + : CatalogStorage() { } @@ -73,45 +73,44 @@ int TsStorage::load(QIODevice* device) { - QTime chrono;chrono.start(); + QTime chrono; chrono.start(); QXmlSimpleReader reader; - reader.setFeature(QStringLiteral("http://qt-project.org/xml/features/report-whitespace-only-CharData"),true); - reader.setFeature(QStringLiteral("http://xml.org/sax/features/namespaces"),false); + reader.setFeature(QStringLiteral("http://qt-project.org/xml/features/report-whitespace-only-CharData"), true); + reader.setFeature(QStringLiteral("http://xml.org/sax/features/namespaces"), false); QXmlInputSource source(device); QString errorMsg; int errorLine;//+errorColumn; - bool success=m_doc.setContent(&source, &reader, &errorMsg, &errorLine/*,errorColumn*/); + bool success = m_doc.setContent(&source, &reader, &errorMsg, &errorLine/*,errorColumn*/); - if (!success) - { - qCWarning(LOKALIZE_LOG)<<"parse error"<actionType==TsContentEditingData::CheckLength)) + || (!result.isEmpty() && data && data->actionType == TsContentEditingData::CheckLength)) return QString(); - bool seenCharacterDataAfterElement=false; + bool seenCharacterDataAfterElement = false; QDomNode n = elem.firstChild(); - while (!n.isNull()) - { - if (n.isCharacterData()) - { - seenCharacterDataAfterElement=true; - - QDomCharacterData c=n.toCharacterData(); - QString cData=c.data(); - - if (data && data->pos!=-1 && - data->pos>=startingPos && data->pos<=startingPos+cData.size()) - { + while (!n.isNull()) { + if (n.isCharacterData()) { + seenCharacterDataAfterElement = true; + + QDomCharacterData c = n.toCharacterData(); + QString cData = c.data(); + + if (data && data->pos != -1 && + data->pos >= startingPos && data->pos <= startingPos + cData.size()) { // time to do some action! ;) - int localStartPos=data->pos-startingPos; + int localStartPos = data->pos - startingPos; //BEGIN DELETE TEXT - if (data->actionType==TsContentEditingData::DeleteText) //(data->lengthOfStringToRemove!=-1) - { - if (localStartPos+data->lengthOfStringToRemove>cData.size()) - { + if (data->actionType == TsContentEditingData::DeleteText) { //(data->lengthOfStringToRemove!=-1) + if (localStartPos + data->lengthOfStringToRemove > cData.size()) { //text is fragmented into several QDomCharacterData - int localDelLen=cData.size()-localStartPos; + int localDelLen = cData.size() - localStartPos; //qCWarning(LOKALIZE_LOG)<<"text is fragmented into several QDomCharacterData. localDelLen:"<lengthOfStringToRemove=data->lengthOfStringToRemove-localDelLen; + data->lengthOfStringToRemove = data->lengthOfStringToRemove - localDelLen; //data->pos=startingPos; //qCWarning(LOKALIZE_LOG)<<"\tsetup:"<pos<lengthOfStringToRemove; - } - else - { + } else { //qCWarning(LOKALIZE_LOG)<<"simple delete"<lengthOfStringToRemove; - c.deleteData(localStartPos,data->lengthOfStringToRemove); - data->actionType=TsContentEditingData::CheckLength; + c.deleteData(localStartPos, data->lengthOfStringToRemove); + data->actionType = TsContentEditingData::CheckLength; return QString('a');//so it exits 100% } } //END DELETE TEXT //INSERT - else if (data->actionType==TsContentEditingData::InsertText) - { - c.insertData(localStartPos,data->stringToInsert); - data->actionType=TsContentEditingData::CheckLength; + else if (data->actionType == TsContentEditingData::InsertText) { + c.insertData(localStartPos, data->stringToInsert); + data->actionType = TsContentEditingData::CheckLength; return QString('a');//so it exits 100% } - cData=c.data(); + cData = c.data(); } //else // if (data&&data->pos!=-1/*&& n.nextSibling().isNull()*/) // qCWarning(LOKALIZE_LOG)<<"arg!"<pos"<pos; result += cData; - startingPos+=cData.size(); + startingPos += cData.size(); } n = n.nextSibling(); } - if (!seenCharacterDataAfterElement) - { + if (!seenCharacterDataAfterElement) { //add empty charData child so that user could add some text - elem.appendChild( elem.ownerDocument().createTextNode(QString()) ); + elem.appendChild(elem.ownerDocument().createTextNode(QString())); } return result; @@ -262,13 +251,13 @@ { CatalogString catalogString; TsContentEditingData data(TsContentEditingData::Get); - catalogString.string=content(contentElement, &data); + catalogString.string = content(contentElement, &data); return catalogString; } CatalogString TsStorage::catalogString(const DocPosition& pos) const { - return catalogString(pos.part==DocPosition::Target?targetForPos(pos):sourceForPos(pos.entry)); + return catalogString(pos.part == DocPosition::Target ? targetForPos(pos) : sourceForPos(pos.entry)); } CatalogString TsStorage::targetWithTags(DocPosition pos) const @@ -292,32 +281,30 @@ void TsStorage::targetDelete(const DocPosition& pos, int count) { - TsContentEditingData data(pos.offset,count); - content(targetForPos(pos),&data); + TsContentEditingData data(pos.offset, count); + content(targetForPos(pos), &data); } void TsStorage::targetInsert(const DocPosition& pos, const QString& arg) { - qCWarning(LOKALIZE_LOG)< - if (targetEl.isNull()) - { - QDomNode unitEl=unitForPos(pos.entry); - QDomNode refNode=unitEl.firstChildElement(names[SourceTag]); - targetEl = unitEl.insertAfter(m_doc.createElement(names[TargetTag]),refNode).toElement(); - - if (pos.entry if (arg.isEmpty()) return; //means we were called just to add tag - TsContentEditingData data(pos.offset,arg); - content(targetEl,&data); + TsContentEditingData data(pos.offset, arg); + content(targetEl, &data); } void TsStorage::setTarget(const DocPosition& pos, const QString& arg) @@ -332,9 +319,9 @@ { QVector result; - QString oldsource=content(unitForPos(pos.entry).firstChildElement(names[OldSourceTag])); + QString oldsource = content(unitForPos(pos.entry).firstChildElement(names[OldSourceTag])); if (!oldsource.isEmpty()) - result< result; QDomElement elem = unitForPos(pos.entry).firstChildElement(names[NoteTag]); - while (!elem.isNull()) - { + while (!elem.isNull()) { Note note; - note.content=elem.text(); + note.content = elem.text(); result.append(note); - elem=elem.nextSiblingElement(names[NoteTag]); + elem = elem.nextSiblingElement(names[NoteTag]); } return result; } @@ -380,54 +365,46 @@ QVector result; QDomElement elem = unitForPos(pos.entry).firstChildElement(names[DevNoteTag]); - while (!elem.isNull()) - { + while (!elem.isNull()) { Note note; - note.content=elem.text(); + note.content = elem.text(); result.append(note); - elem=elem.nextSiblingElement(names[DevNoteTag]); + elem = elem.nextSiblingElement(names[DevNoteTag]); } return result; } Note TsStorage::setNote(DocPosition pos, const Note& note) { //qCWarning(LOKALIZE_LOG)< if needed - QDomElement target=unitForPos(pos.entry).firstChildElement(names[TargetTag]); //asking directly to bypass plural state detection - if (target.attribute(attrnames[TypeAttr])==attrvalues[ObsoleteVal]) + targetInsert(pos, QString()); //adds if needed + QDomElement target = unitForPos(pos.entry).firstChildElement(names[TargetTag]); //asking directly to bypass plural state detection + if (target.attribute(attrnames[TypeAttr]) == attrvalues[ObsoleteVal]) return; if (approved) target.removeAttribute(attrnames[TypeAttr]); else - target.setAttribute(attrnames[TypeAttr],QStringLiteral("unfinished")); + target.setAttribute(attrnames[TypeAttr], QStringLiteral("unfinished")); } bool TsStorage::isApproved(const DocPosition& pos) const { - QDomElement target=unitForPos(pos.entry).firstChildElement(names[TargetTag]); - return !target.hasAttribute(attrnames[TypeAttr]) || target.attribute(attrnames[TypeAttr])==attrvalues[VanishedVal]; + QDomElement target = unitForPos(pos.entry).firstChildElement(names[TargetTag]); + return !target.hasAttribute(attrnames[TypeAttr]) || target.attribute(attrnames[TypeAttr]) == attrvalues[VanishedVal]; } bool TsStorage::isObsolete(int entry) const { - QDomElement target=unitForPos(entry).firstChildElement(names[TargetTag]); - QString v=target.attribute(attrnames[TypeAttr]); - return v==attrvalues[ObsoleteVal] || v==attrvalues[VanishedVal]; + QDomElement target = unitForPos(entry).firstChildElement(names[TargetTag]); + QString v = target.attribute(attrnames[TypeAttr]); + return v == attrvalues[ObsoleteVal] || v == attrvalues[VanishedVal]; } bool TsStorage::isEmpty(const DocPosition& pos) const { TsContentEditingData data(TsContentEditingData::CheckLength); - return content(targetForPos(pos),&data).isEmpty(); + return content(targetForPos(pos), &data).isEmpty(); } bool TsStorage::isEquivTrans(const DocPosition& pos) const @@ -524,16 +501,16 @@ QDomElement TsStorage::targetForPos(DocPosition pos) const { - QDomElement unit=unitForPos(pos.entry); - QDomElement translation=unit.firstChildElement(names[TargetTag]); + QDomElement unit = unitForPos(pos.entry); + QDomElement translation = unit.firstChildElement(names[TargetTag]); if (!unit.hasAttribute(names[PluralTag])) return translation; - - if (pos.form==-1) pos.form=0; - - QDomNodeList forms=translation.elementsByTagName(QStringLiteral("numerusform")); - while (pos.form>=forms.size()) - translation.appendChild( unit.ownerDocument().createElement(QStringLiteral("numerusform")) ); + + if (pos.form == -1) pos.form = 0; + + QDomNodeList forms = translation.elementsByTagName(QStringLiteral("numerusform")); + while (pos.form >= forms.size()) + translation.appendChild(unit.ownerDocument().createElement(QStringLiteral("numerusform"))); return forms.at(pos.form).toElement(); } @@ -544,12 +521,11 @@ void TsStorage::setTargetLangCode(const QString& langCode) { - m_targetLangCode=langCode; + m_targetLangCode = langCode; - QDomElement file=m_doc.elementsByTagName(QStringLiteral("TS")).at(0).toElement(); - if (m_targetLangCode!=file.attribute(QStringLiteral("language")).replace('-', '_')) - { - QString l=langCode; + QDomElement file = m_doc.elementsByTagName(QStringLiteral("TS")).at(0).toElement(); + if (m_targetLangCode != file.attribute(QStringLiteral("language")).replace('-', '_')) { + QString l = langCode; file.setAttribute(QStringLiteral("language"), l.replace('_', '-')); } } diff --git a/src/catalog/xliff/xliffstorage.h b/src/catalog/xliff/xliffstorage.h --- a/src/catalog/xliff/xliffstorage.h +++ b/src/catalog/xliff/xliffstorage.h @@ -39,7 +39,7 @@ int capabilities() const; int load(QIODevice* device); - bool save(QIODevice* device, bool belongsToProject=false); + bool save(QIODevice* device, bool belongsToProject = false); int size() const; bool isEmpty() const; @@ -52,8 +52,14 @@ CatalogString catalogString(const DocPosition& pos) const; /// all plural forms. pos.form doesn't matter TODO - QStringList sourceAllForms(const DocPosition& pos, bool stripNewLines=false) const{Q_UNUSED(pos) Q_UNUSED(stripNewLines) return QStringList();} - QStringList targetAllForms(const DocPosition& pos, bool stripNewLines=false) const{Q_UNUSED(pos) Q_UNUSED(stripNewLines) return QStringList();} + QStringList sourceAllForms(const DocPosition& pos, bool stripNewLines = false) const + { + Q_UNUSED(pos) Q_UNUSED(stripNewLines) return QStringList(); + } + QStringList targetAllForms(const DocPosition& pos, bool stripNewLines = false) const + { + Q_UNUSED(pos) Q_UNUSED(stripNewLines) return QStringList(); + } void targetDelete(const DocPosition& pos, int count); void targetInsert(const DocPosition& pos, const QString& arg); @@ -63,7 +69,7 @@ Phase updatePhase(const Phase& phase); QList allPhases() const; Phase phase(const QString& name) const; - QMap allTools() const; + QMap allTools() const; QVector phaseNotes(const QString& phase) const; QVector setPhaseNotes(const QString& phase, QVector notes); @@ -97,9 +103,18 @@ int binUnitsCount() const; int unitById(const QString& id) const; - QString mimetype()const{return QStringLiteral("application/x-xliff");} - QString fileType()const{return QStringLiteral("XLIFF (*.xliff *.xlf)");} - CatalogType type()const{return Xliff;} + QString mimetype()const + { + return QStringLiteral("application/x-xliff"); + } + QString fileType()const + { + return QStringLiteral("XLIFF (*.xliff *.xlf)"); + } + CatalogType type()const + { + return Xliff; + } QString originalOdfFilePath(); void setOriginalOdfFilePath(const QString&); @@ -118,7 +133,7 @@ QDomNodeList entries; QDomNodeList binEntries; - QMap m_unitsById; + QMap m_unitsById; }; diff --git a/src/catalog/xliff/xliffstorage.cpp b/src/catalog/xliff/xliffstorage.cpp --- a/src/catalog/xliff/xliffstorage.cpp +++ b/src/catalog/xliff/xliffstorage.cpp @@ -43,12 +43,12 @@ #define U QStringLiteral #endif -static const QString noyes[]={U("no"),U("yes")}; -static const QString bintargettarget[]={U("bin-target"),U("target")}; -static const QString binsourcesource[]={U("bin-source"),U("source")}; -static const QString NOTE=U("note"); +static const QString noyes[] = {U("no"), U("yes")}; +static const QString bintargettarget[] = {U("bin-target"), U("target")}; +static const QString binsourcesource[] = {U("bin-source"), U("source")}; +static const QString NOTE = U("note"); XliffStorage::XliffStorage() - : CatalogStorage() + : CatalogStorage() { } @@ -58,74 +58,70 @@ int XliffStorage::capabilities() const { - return KeepsNoteAuthors|MultipleNotes|Phases|ExtendedStates|Tags; + return KeepsNoteAuthors | MultipleNotes | Phases | ExtendedStates | Tags; } //BEGIN OPEN/SAVE int XliffStorage::load(QIODevice* device) { - QTime chrono;chrono.start(); + QTime chrono; chrono.start(); QXmlSimpleReader reader; - reader.setFeature(QStringLiteral("http://qt-project.org/xml/features/report-whitespace-only-CharData"),true); - reader.setFeature(QStringLiteral("http://xml.org/sax/features/namespaces"),false); + reader.setFeature(QStringLiteral("http://qt-project.org/xml/features/report-whitespace-only-CharData"), true); + reader.setFeature(QStringLiteral("http://xml.org/sax/features/namespaces"), false); QXmlInputSource source(device); QString errorMsg; int errorLine;//+errorColumn; - bool success=m_doc.setContent(&source, &reader, &errorMsg, &errorLine/*,errorColumn*/); + bool success = m_doc.setContent(&source, &reader, &errorMsg, &errorLine/*,errorColumn*/); - QString FILE=QStringLiteral("file"); - if (!success || m_doc.elementsByTagName(FILE).isEmpty()) - { - qCWarning(LOKALIZE_LOG)<0 && (++i) 0 && (++i) < size) { + QDomElement p = entries.at(i).parentNode().toElement(); + if (p.tagName() == QLatin1String("group") && p.attribute(QStringLiteral("restype")) == QLatin1String("x-gettext-plurals")) continue; parentElement.appendChild(entries.at(m_map.last()).cloneNode()); } } } - binEntries=m_doc.elementsByTagName(QStringLiteral("bin-unit")); - size=binEntries.size(); - int offset=m_map.size(); - for(int i=0;i tags; QString stringToInsert; int pos; int lengthOfStringToRemove; ActionType actionType; ///Get - ContentEditingData(ActionType type=Get) - : pos(-1) - , lengthOfStringToRemove(-1) - , actionType(type) + ContentEditingData(ActionType type = Get) + : pos(-1) + , lengthOfStringToRemove(-1) + , actionType(type) {} ///DeleteText ContentEditingData(int p, int l) - : pos(p) - , lengthOfStringToRemove(l) - , actionType(DeleteText) + : pos(p) + , lengthOfStringToRemove(l) + , actionType(DeleteText) {} ///InsertText - ContentEditingData(int p,const QString& s) - : stringToInsert(s) - , pos(p) - , lengthOfStringToRemove(-1) - , actionType(InsertText) + ContentEditingData(int p, const QString& s) + : stringToInsert(s) + , pos(p) + , lengthOfStringToRemove(-1) + , actionType(InsertText) {} ///InsertTag - ContentEditingData(int p,const InlineTag& range) - : pos(p) - , lengthOfStringToRemove(-1) - , actionType(InsertTag) + ContentEditingData(int p, const InlineTag& range) + : pos(p) + , lengthOfStringToRemove(-1) + , actionType(InsertTag) { tags.append(range); } ///DeleteTag ContentEditingData(int p) - : pos(p) - , lengthOfStringToRemove(-1) - , actionType(DeleteTag) + : pos(p) + , lengthOfStringToRemove(-1) + , actionType(DeleteTag) {} }; @@ -258,7 +251,7 @@ * - deletes content, or * - inserts content */ -static QString content(QDomElement elem, ContentEditingData* data=0) +static QString content(QDomElement elem, ContentEditingData* data = 0) { return doContent(elem, 0, data); } @@ -270,225 +263,205 @@ QString result; if (elem.isNull() - || (!result.isEmpty() && data && data->actionType==ContentEditingData::CheckLength)) + || (!result.isEmpty() && data && data->actionType == ContentEditingData::CheckLength)) return QString(); - bool seenCharacterDataAfterElement=false; + bool seenCharacterDataAfterElement = false; QDomNode n = elem.firstChild(); - while (!n.isNull()) - { - if (n.isCharacterData()) - { - seenCharacterDataAfterElement=true; + while (!n.isNull()) { + if (n.isCharacterData()) { + seenCharacterDataAfterElement = true; - QDomCharacterData c=n.toCharacterData(); - QString cData=c.data(); + QDomCharacterData c = n.toCharacterData(); + QString cData = c.data(); - if (data && data->pos!=-1 && - data->pos>=startingPos && data->pos<=startingPos+cData.size()) - { + if (data && data->pos != -1 && + data->pos >= startingPos && data->pos <= startingPos + cData.size()) { // time to do some action! ;) - int localStartPos=data->pos-startingPos; + int localStartPos = data->pos - startingPos; //BEGIN DELETE TEXT - if (data->actionType==ContentEditingData::DeleteText) //(data->lengthOfStringToRemove!=-1) - { - if (localStartPos+data->lengthOfStringToRemove>cData.size()) - { + if (data->actionType == ContentEditingData::DeleteText) { //(data->lengthOfStringToRemove!=-1) + if (localStartPos + data->lengthOfStringToRemove > cData.size()) { //text is fragmented into several QDomCharacterData - int localDelLen=cData.size()-localStartPos; + int localDelLen = cData.size() - localStartPos; //qCWarning(LOKALIZE_LOG)<<"text is fragmented into several QDomCharacterData. localDelLen:"<lengthOfStringToRemove=data->lengthOfStringToRemove-localDelLen; + data->lengthOfStringToRemove = data->lengthOfStringToRemove - localDelLen; //data->pos=startingPos; //qCWarning(LOKALIZE_LOG)<<"\tsetup:"<pos<lengthOfStringToRemove; - } - else - { + } else { //qCWarning(LOKALIZE_LOG)<<"simple delete"<lengthOfStringToRemove; - c.deleteData(localStartPos,data->lengthOfStringToRemove); - data->actionType=ContentEditingData::CheckLength; + c.deleteData(localStartPos, data->lengthOfStringToRemove); + data->actionType = ContentEditingData::CheckLength; return QString('a');//so it exits 100% } } //END DELETE TEXT //INSERT - else if (data->actionType==ContentEditingData::InsertText) - { - c.insertData(localStartPos,data->stringToInsert); - data->actionType=ContentEditingData::CheckLength; + else if (data->actionType == ContentEditingData::InsertText) { + c.insertData(localStartPos, data->stringToInsert); + data->actionType = ContentEditingData::CheckLength; return QString('a');//so it exits 100% } //BEGIN INSERT TAG - else if (data->actionType==ContentEditingData::InsertTag) - { - const InlineTag& tag=data->tags.first(); - QString mid=cData.mid(localStartPos); - qCDebug(LOKALIZE_LOG)<<"inserting tag"<pos<actionType == ContentEditingData::InsertTag) { + const InlineTag& tag = data->tags.first(); + QString mid = cData.mid(localStartPos); + qCDebug(LOKALIZE_LOG) << "inserting tag" << tag.name() << tag.id << tag.start << tag.end << mid << data->pos << startingPos; if (mid.size()) - c.deleteData(localStartPos,mid.size()); - QDomElement newNode=elem.insertAfter( elem.ownerDocument().createElement(tag.getElementName()),n).toElement(); - newNode.setAttribute(QStringLiteral("id"),tag.id); + c.deleteData(localStartPos, mid.size()); + QDomElement newNode = elem.insertAfter(elem.ownerDocument().createElement(tag.getElementName()), n).toElement(); + newNode.setAttribute(QStringLiteral("id"), tag.id); if (!tag.xid.isEmpty()) - newNode.setAttribute(QStringLiteral("xid"),tag.xid); + newNode.setAttribute(QStringLiteral("xid"), tag.xid); - if (tag.isPaired()&&tag.end>(tag.start+1)) - { + if (tag.isPaired() && tag.end > (tag.start + 1)) { //qCWarning(LOKALIZE_LOG)<<"isPaired"; - int len=tag.end-tag.start-1;//-image symbol - int localLen=qMin(len,mid.size()); - if (localLen)//appending text - { + int len = tag.end - tag.start - 1; //-image symbol + int localLen = qMin(len, mid.size()); + if (localLen) { //appending text //qCWarning(LOKALIZE_LOG)<<"localLen. appending"<missingLen (or siblings end) - int childrenCumulativeLen=0; - QDomNode sibling=newNode.nextSibling(); - while(!sibling.isNull())//&&(childrenCumulativeLenmissingLen) - { - if (tmp.isCharacterData()) - { + if (childrenCumulativeLen > missingLen) { + if (tmp.isCharacterData()) { //divide the last string - const QString& endData=tmp.toCharacterData().data(); - QString last=endData.left(endData.size()-(childrenCumulativeLen-missingLen)); - newNode.appendChild( elem.ownerDocument().createTextNode(last)); - tmp.toCharacterData().deleteData(0,last.size()); + const QString& endData = tmp.toCharacterData().data(); + QString last = endData.left(endData.size() - (childrenCumulativeLen - missingLen)); + newNode.appendChild(elem.ownerDocument().createTextNode(last)); + tmp.toCharacterData().deleteData(0, last.size()); //qCWarning(LOKALIZE_LOG)<<"end of add"<actionType=ContentEditingData::CheckLength; + data->actionType = ContentEditingData::CheckLength; return QStringLiteral("a");//we're done here } //END INSERT TAG - cData=c.data(); + cData = c.data(); } //else // if (data&&data->pos!=-1/*&& n.nextSibling().isNull()*/) // qCWarning(LOKALIZE_LOG)<<"arg!"<pos"<pos; result += cData; - startingPos+=cData.size(); - } - else if (n.isElement()) - { - QDomElement el=n.toElement(); + startingPos += cData.size(); + } else if (n.isElement()) { + QDomElement el = n.toElement(); //BEGIN DELETE TAG - if (data&&data->actionType==ContentEditingData::DeleteTag - &&data->pos==startingPos) - { + if (data && data->actionType == ContentEditingData::DeleteTag + && data->pos == startingPos) { //qCWarning(LOKALIZE_LOG)<<"start deleting tag"; data->tags.append(InlineTag(startingPos, -1, InlineTag::getElementType(el.tagName().toUtf8()), el.attribute("id"), el.attribute("xid"))); - if (data->tags.first().isPaired()) - { + if (data->tags.first().isPaired()) { //get end position ContentEditingData subData(ContentEditingData::Get); - QString subContent=doContent(el,startingPos,&subData); - data->tags[0].end=1+startingPos+subContent.size();//tagsymbol+text + QString subContent = doContent(el, startingPos, &subData); + data->tags[0].end = 1 + startingPos + subContent.size(); //tagsymbol+text //qCWarning(LOKALIZE_LOG)<<"get end position"<actionType=ContentEditingData::CheckLength; + data->actionType = ContentEditingData::CheckLength; return QStringLiteral("a");//we're done here } //END DELETE TAG if (!seenCharacterDataAfterElement) //add empty charData child so that user could add some text - elem.insertBefore( elem.ownerDocument().createTextNode(QString()),n); - seenCharacterDataAfterElement=false; + elem.insertBefore(elem.ownerDocument().createTextNode(QString()), n); + seenCharacterDataAfterElement = false; - if (data) - {result += QChar(TAGRANGE_IMAGE_SYMBOL); ++startingPos;} - int oldStartingPos=startingPos; + if (data) { + result += QChar(TAGRANGE_IMAGE_SYMBOL); + ++startingPos; + } + int oldStartingPos = startingPos; //detect type of the tag - InlineTag::InlineElement i=InlineTag::getElementType(el.tagName().toUtf8()); + InlineTag::InlineElement i = InlineTag::getElementType(el.tagName().toUtf8()); //1 or 2 images to represent it? //2 = there may be content inside - if (InlineTag::isPaired(i)) - { - QString recursiveContent=doContent(el,startingPos,data); - if (!recursiveContent.isEmpty()) - {result += recursiveContent; startingPos+=recursiveContent.size();} - if (data) - {result += QChar(TAGRANGE_IMAGE_SYMBOL); ++startingPos;} + if (InlineTag::isPaired(i)) { + QString recursiveContent = doContent(el, startingPos, data); + if (!recursiveContent.isEmpty()) { + result += recursiveContent; + startingPos += recursiveContent.size(); + } + if (data) { + result += QChar(TAGRANGE_IMAGE_SYMBOL); + ++startingPos; + } } - if (data&&data->actionType==ContentEditingData::Get) - { - QString id=el.attribute(QStringLiteral("id")); - if (i==InlineTag::mrk)//TODO attr map - id=el.attribute(QStringLiteral("mtype")); + if (data && data->actionType == ContentEditingData::Get) { + QString id = el.attribute(QStringLiteral("id")); + if (i == InlineTag::mrk) //TODO attr map + id = el.attribute(QStringLiteral("mtype")); //qCWarning(LOKALIZE_LOG)<<"tagName"<tags.append(InlineTag(oldStartingPos-1,startingPos-1,i,id,el.attribute(QStringLiteral("xid")))); + data->tags.append(InlineTag(oldStartingPos - 1, startingPos - 1, i, id, el.attribute(QStringLiteral("xid")))); } } n = n.nextSibling(); } - if (!seenCharacterDataAfterElement) - { + if (!seenCharacterDataAfterElement) { //add empty charData child so that user could add some text - elem.appendChild( elem.ownerDocument().createTextNode(QString())); + elem.appendChild(elem.ownerDocument().createTextNode(QString())); } return result; @@ -500,13 +473,13 @@ CatalogString XliffStorage::catalogString(QDomElement unit, DocPosition::Part part) const { - static const QString names[]={U("source"),U("target"), U("seg-source")}; + static const QString names[] = {U("source"), U("target"), U("seg-source")}; CatalogString catalogString; ContentEditingData data(ContentEditingData::Get); - int nameIndex=part==DocPosition::Target; - if (nameIndex==0 && !unit.firstChildElement(names[2]).isNull()) nameIndex=2; - catalogString.string=content(unit.firstChildElement( names[nameIndex]), &data ); - catalogString.tags=data.tags; + int nameIndex = part == DocPosition::Target; + if (nameIndex == 0 && !unit.firstChildElement(names[2]).isNull()) nameIndex = 2; + catalogString.string = content(unit.firstChildElement(names[nameIndex]), &data); + catalogString.tags = data.tags; return catalogString; } @@ -526,79 +499,73 @@ static QString genericContent(QDomElement elem, bool nonbin) { - return nonbin?content(elem):elem.firstChildElement(QStringLiteral("external-file")).attribute(QStringLiteral("href")); + return nonbin ? content(elem) : elem.firstChildElement(QStringLiteral("external-file")).attribute(QStringLiteral("href")); } QString XliffStorage::source(const DocPosition& pos) const { - return genericContent(sourceForPos(pos.entry),pos.entry - if (targetEl.isNull()) - { - QDomNode unitEl=unitForPos(pos.entry); - QDomNode refNode=unitEl.firstChildElement(QStringLiteral("seg-source"));//obey standard - if (refNode.isNull()) refNode=unitEl.firstChildElement(binsourcesource[pos.entry if (arg.isEmpty()) return; //means we were called just to add tag - if (pos.entry>=size()) - { - QDomElement ef=targetEl.firstChildElement(QStringLiteral("external-file")); + if (pos.entry >= size()) { + QDomElement ef = targetEl.firstChildElement(QStringLiteral("external-file")); if (ef.isNull()) - ef=targetEl.appendChild(m_doc.createElement(QStringLiteral("external-file"))).toElement(); - ef.setAttribute(QStringLiteral("href"),arg); + ef = targetEl.appendChild(m_doc.createElement(QStringLiteral("external-file"))).toElement(); + ef.setAttribute(QStringLiteral("href"), arg); return; } - ContentEditingData data(pos.offset,arg); - content(targetEl,&data); + ContentEditingData data(pos.offset, arg); + content(targetEl, &data); } void XliffStorage::targetInsertTag(const DocPosition& pos, const InlineTag& tag) { - targetInsert(pos,QString()); //adds if needed - ContentEditingData data(tag.start,tag); - content(targetForPos(pos.entry),&data); + targetInsert(pos, QString()); //adds if needed + ContentEditingData data(tag.start, tag); + content(targetForPos(pos.entry), &data); } InlineTag XliffStorage::targetDeleteTag(const DocPosition& pos) { ContentEditingData data(pos.offset); - content(targetForPos(pos.entry),&data); - if (data.tags[0].end==-1) data.tags[0].end=data.tags[0].start; + content(targetForPos(pos.entry), &data); + if (data.tags[0].end == -1) data.tags[0].end = data.tags[0].start; return data.tags.first(); } @@ -615,134 +582,129 @@ QVector result; QDomElement elem = unitForPos(pos.entry).firstChildElement(QStringLiteral("alt-trans")); - while (!elem.isNull()) - { + while (!elem.isNull()) { AltTrans aTrans; - aTrans.source=catalogString(elem, DocPosition::Source); - aTrans.target=catalogString(elem, DocPosition::Target); - aTrans.phase=elem.attribute(QStringLiteral("phase-name")); - aTrans.origin=elem.attribute(QStringLiteral("origin")); - aTrans.score=elem.attribute(QStringLiteral("match-quality")).toInt(); - aTrans.lang=elem.firstChildElement(QStringLiteral("target")).attribute(QStringLiteral("xml:lang")); - - const char* const types[]={ + aTrans.source = catalogString(elem, DocPosition::Source); + aTrans.target = catalogString(elem, DocPosition::Target); + aTrans.phase = elem.attribute(QStringLiteral("phase-name")); + aTrans.origin = elem.attribute(QStringLiteral("origin")); + aTrans.score = elem.attribute(QStringLiteral("match-quality")).toInt(); + aTrans.lang = elem.firstChildElement(QStringLiteral("target")).attribute(QStringLiteral("xml:lang")); + + const char* const types[] = { "proposal", "previous-version", "rejected", "reference", "accepted" }; - QString typeStr=elem.attribute(QStringLiteral("alttranstype")); - int i=-1; - while (++i XliffStorage::allPhases() const { QList result; - QDomElement file=m_doc.elementsByTagName(QStringLiteral("file")).at(0).toElement(); - QDomElement header=file.firstChildElement(QStringLiteral("header")); - QDomElement phasegroup=header.firstChildElement(QStringLiteral("phase-group")); - QDomElement phaseElem=phasegroup.firstChildElement(QStringLiteral("phase")); - while (!phaseElem.isNull()) - { + QDomElement file = m_doc.elementsByTagName(QStringLiteral("file")).at(0).toElement(); + QDomElement header = file.firstChildElement(QStringLiteral("header")); + QDomElement phasegroup = header.firstChildElement(QStringLiteral("phase-group")); + QDomElement phaseElem = phasegroup.firstChildElement(QStringLiteral("phase")); + while (!phaseElem.isNull()) { result.append(phaseFromElement(phaseElem)); - phaseElem=phaseElem.nextSiblingElement(QStringLiteral("phase")); + phaseElem = phaseElem.nextSiblingElement(QStringLiteral("phase")); } return result; } Phase XliffStorage::phase(const QString& name) const { QDomElement phasegroup; - QDomElement phaseElem=phaseElement(m_doc,name,phasegroup); + QDomElement phaseElem = phaseElement(m_doc, name, phasegroup); return phaseFromElement(phaseElem); } -QMap XliffStorage::allTools() const +QMap XliffStorage::allTools() const { - QMap result; - QDomElement file=m_doc.elementsByTagName(QStringLiteral("file")).at(0).toElement(); - QDomElement header=file.firstChildElement(QStringLiteral("header")); - QDomElement toolElem=header.firstChildElement(QStringLiteral("tool")); - while (!toolElem.isNull()) - { + QMap result; + QDomElement file = m_doc.elementsByTagName(QStringLiteral("file")).at(0).toElement(); + QDomElement header = file.firstChildElement(QStringLiteral("header")); + QDomElement toolElem = header.firstChildElement(QStringLiteral("tool")); + while (!toolElem.isNull()) { Tool tool; - tool.tool =toolElem.attribute(QStringLiteral("tool-id")); - tool.name =toolElem.attribute(QStringLiteral("tool-name")); - tool.version =toolElem.attribute(QStringLiteral("tool-version")); - tool.company =toolElem.attribute(QStringLiteral("tool-company")); + tool.tool = toolElem.attribute(QStringLiteral("tool-id")); + tool.name = toolElem.attribute(QStringLiteral("tool-name")); + tool.version = toolElem.attribute(QStringLiteral("tool-version")); + tool.company = toolElem.attribute(QStringLiteral("tool-company")); result.insert(tool.tool, tool); - toolElem=toolElem.nextSiblingElement(QStringLiteral("tool")); + toolElem = toolElem.nextSiblingElement(QStringLiteral("tool")); } return result; } @@ -752,59 +714,55 @@ QStringList result; QDomElement elem = unitForPos(pos.entry).firstChildElement(QStringLiteral("context-group")); - while (!elem.isNull()) - { - if (elem.attribute(QStringLiteral("purpose")).contains(QLatin1String("location"))) - { + while (!elem.isNull()) { + if (elem.attribute(QStringLiteral("purpose")).contains(QLatin1String("location"))) { QDomElement context = elem.firstChildElement(QStringLiteral("context")); - while (!context.isNull()) - { + while (!context.isNull()) { QString sourcefile; QString linenumber; const QString contextType = context.attribute(QStringLiteral("context-type")); if (contextType == QLatin1String("sourcefile")) sourcefile = context.text(); else if (contextType == QLatin1String("linenumber")) linenumber = context.text(); - if (!( sourcefile.isEmpty() && linenumber.isEmpty() )) + if (!(sourcefile.isEmpty() && linenumber.isEmpty())) result.append(sourcefile % ':' % linenumber); - context=context.nextSiblingElement(QStringLiteral("context")); + context = context.nextSiblingElement(QStringLiteral("context")); } } - elem=elem.nextSiblingElement(QStringLiteral("context-group")); + elem = elem.nextSiblingElement(QStringLiteral("context-group")); } //qSort(result); return result; } static void initNoteFromElement(Note& note, QDomElement elem) { - note.content=elem.text(); - note.from=elem.attribute(QStringLiteral("from")); - note.lang=elem.attribute(QStringLiteral("xml:lang")); - if (elem.attribute(QStringLiteral("annotates"))==QLatin1String("source")) - note.annotates=Note::Source; - else if (elem.attribute(QStringLiteral("annotates"))==QLatin1String("target")) - note.annotates=Note::Target; + note.content = elem.text(); + note.from = elem.attribute(QStringLiteral("from")); + note.lang = elem.attribute(QStringLiteral("xml:lang")); + if (elem.attribute(QStringLiteral("annotates")) == QLatin1String("source")) + note.annotates = Note::Source; + else if (elem.attribute(QStringLiteral("annotates")) == QLatin1String("target")) + note.annotates = Note::Target; bool ok; - note.priority=elem.attribute(QStringLiteral("priority")).toInt(&ok); - if (!ok) note.priority=0; + note.priority = elem.attribute(QStringLiteral("priority")).toInt(&ok); + if (!ok) note.priority = 0; } QVector XliffStorage::notes(const DocPosition& pos) const { QList result; QDomElement elem = entries.at(m_map.at(pos.entry)).firstChildElement(NOTE); - while (!elem.isNull()) - { + while (!elem.isNull()) { Note note; - initNoteFromElement(note,elem); + initNoteFromElement(note, elem); result.append(note); - elem=elem.nextSiblingElement(NOTE); + elem = elem.nextSiblingElement(NOTE); } qSort(result); return result.toVector(); @@ -820,75 +778,66 @@ Note XliffStorage::setNote(DocPosition pos, const Note& note) { //qCWarning(LOKALIZE_LOG)< result; - QDomNodeList notes=m_doc.elementsByTagName(NOTE); - int i=notes.size(); - while (--i>=0) - { - QString from=notes.at(i).toElement().attribute(QStringLiteral("from")); + QDomNodeList notes = m_doc.elementsByTagName(NOTE); + int i = notes.size(); + while (--i >= 0) { + QString from = notes.at(i).toElement().attribute(QStringLiteral("from")); if (!from.isEmpty()) result.insert(from); } return result.toList(); } -QVector phaseNotes(QDomDocument m_doc, const QString& phasename, bool remove=false) +QVector phaseNotes(QDomDocument m_doc, const QString& phasename, bool remove = false) { QVector result; QDomElement phasegroup; - QDomElement phaseElem=phaseElement(m_doc,phasename,phasegroup); + QDomElement phaseElem = phaseElement(m_doc, phasename, phasegroup); - QDomElement noteElem=phaseElem.firstChildElement(NOTE); - while (!noteElem.isNull()) - { + QDomElement noteElem = phaseElem.firstChildElement(NOTE); + while (!noteElem.isNull()) { Note note; - initNoteFromElement(note,noteElem); + initNoteFromElement(note, noteElem); result.append(note); - QDomElement old=noteElem; - noteElem=noteElem.nextSiblingElement(NOTE); + QDomElement old = noteElem; + noteElem = noteElem.nextSiblingElement(NOTE); if (remove) phaseElem.removeChild(old); } return result; @@ -901,41 +850,40 @@ QVector XliffStorage::setPhaseNotes(const QString& phasename, QVector notes) { - QVector result=::phaseNotes(m_doc, phasename, true); + QVector result =::phaseNotes(m_doc, phasename, true); QDomElement phasegroup; - QDomElement phaseElem=phaseElement(m_doc,phasename,phasegroup); + QDomElement phaseElem = phaseElement(m_doc, phasename, phasegroup); - foreach(const Note& note, notes) - { - QDomElement elem=phaseElem.appendChild(m_doc.createElement(NOTE)).toElement(); + foreach (const Note& note, notes) { + QDomElement elem = phaseElem.appendChild(m_doc.createElement(NOTE)).toElement(); elem.appendChild(m_doc.createTextNode(note.content)); - if (!note.from.isEmpty()) elem.setAttribute(QStringLiteral("from"),note.from); - if (note.priority) elem.setAttribute(QStringLiteral("priority"),note.priority); + if (!note.from.isEmpty()) elem.setAttribute(QStringLiteral("from"), note.from); + if (note.priority) elem.setAttribute(QStringLiteral("priority"), note.priority); } return result; } QString XliffStorage::setPhase(const DocPosition& pos, const QString& phase) { - QString PHASENAME=QStringLiteral("phase-name"); - targetInsert(pos,QString()); //adds if needed + QString PHASENAME = QStringLiteral("phase-name"); + targetInsert(pos, QString()); //adds if needed - QDomElement target=targetForPos(pos.entry); - QString result=target.attribute(PHASENAME); + QDomElement target = targetForPos(pos.entry); + QString result = target.attribute(PHASENAME); if (phase.isEmpty()) target.removeAttribute(PHASENAME); - else if (phase!=result) - target.setAttribute(PHASENAME,phase); + else if (phase != result) + target.setAttribute(PHASENAME, phase); return result; } QString XliffStorage::phase(const DocPosition& pos) const { - QDomElement target=targetForPos(pos.entry); + QDomElement target = targetForPos(pos.entry); return target.attribute(QStringLiteral("phase-name")); } @@ -973,71 +921,72 @@ } */ -static const QString xliff_states[]={ +static const QString xliff_states[] = { U("new"), U("needs-translation"), U("needs-l10n"), U("needs-adaptation"), U("translated"), U("needs-review-translation"), U("needs-review-l10n"), U("needs-review-adaptation"), - U("final"), U("signed-off")}; + U("final"), U("signed-off") +}; TargetState stringToState(const QString& state) { - int i=sizeof(xliff_states)/sizeof(QString); - while (--i>0 && state!=xliff_states[i]) + int i = sizeof(xliff_states) / sizeof(QString); + while (--i > 0 && state != xliff_states[i]) ; return TargetState(i); } TargetState XliffStorage::setState(const DocPosition& pos, TargetState state) { - targetInsert(pos,QString()); //adds if needed - QDomElement target=targetForPos(pos.entry); - TargetState prev=stringToState(target.attribute(QStringLiteral("state"))); - target.setAttribute(QStringLiteral("state"),xliff_states[state]); + targetInsert(pos, QString()); //adds if needed + QDomElement target = targetForPos(pos.entry); + TargetState prev = stringToState(target.attribute(QStringLiteral("state"))); + target.setAttribute(QStringLiteral("state"), xliff_states[state]); - unitForPos(pos.entry).setAttribute(QStringLiteral("approved"), noyes[state==SignedOff]); + unitForPos(pos.entry).setAttribute(QStringLiteral("approved"), noyes[state == SignedOff]); return prev; } TargetState XliffStorage::state(const DocPosition& pos) const { - QDomElement target=targetForPos(pos.entry); - if (!target.hasAttribute(QStringLiteral("state")) && unitForPos(pos.entry).attribute(QStringLiteral("approved"))==QLatin1String("yes")) + QDomElement target = targetForPos(pos.entry); + if (!target.hasAttribute(QStringLiteral("state")) && unitForPos(pos.entry).attribute(QStringLiteral("approved")) == QLatin1String("yes")) return SignedOff; return stringToState(target.attribute(QStringLiteral("state"))); } bool XliffStorage::isEmpty(const DocPosition& pos) const { ContentEditingData data(ContentEditingData::CheckLength); - return content(targetForPos(pos.entry),&data).isEmpty(); + return content(targetForPos(pos.entry), &data).isEmpty(); } bool XliffStorage::isEquivTrans(const DocPosition& pos) const { - return targetForPos(pos.entry).attribute(QStringLiteral("equiv-trans"))!=QLatin1String("no"); + return targetForPos(pos.entry).attribute(QStringLiteral("equiv-trans")) != QLatin1String("no"); } void XliffStorage::setEquivTrans(const DocPosition& pos, bool equivTrans) { - targetForPos(pos.entry).setAttribute(QStringLiteral("equiv-trans"),noyes[equivTrans]); + targetForPos(pos.entry).setAttribute(QStringLiteral("equiv-trans"), noyes[equivTrans]); } QDomElement XliffStorage::unitForPos(int pos) const { - if (poskey() == Qt::Key_Return && currentIndex().isValid()) { emit clicked(currentIndex()); e->accept(); @@ -71,37 +72,37 @@ CatalogView::CatalogView(QWidget* parent, Catalog* catalog) - : QDockWidget ( i18nc("@title:window aka Message Tree","Translation Units"), parent) + : QDockWidget(i18nc("@title:window aka Message Tree", "Translation Units"), parent) , m_browser(new CatalogTreeView(this)) , m_lineEdit(new QLineEdit(this)) - , m_model(new CatalogTreeModel(this,catalog)) + , m_model(new CatalogTreeModel(this, catalog)) , m_proxyModel(new CatalogTreeFilterModel(this)) { setObjectName(QStringLiteral("catalogTreeView")); - QWidget* w=new QWidget(this); - QVBoxLayout* layout=new QVBoxLayout(w); - layout->setContentsMargins(0,0,0,0); - QHBoxLayout* l=new QHBoxLayout; - l->setContentsMargins(0,0,0,0); + QWidget* w = new QWidget(this); + QVBoxLayout* layout = new QVBoxLayout(w); + layout->setContentsMargins(0, 0, 0, 0); + QHBoxLayout* l = new QHBoxLayout; + l->setContentsMargins(0, 0, 0, 0); l->setSpacing(0); layout->addLayout(l); m_lineEdit->setClearButtonEnabled(true); m_lineEdit->setPlaceholderText(i18n("Quick search...")); - m_lineEdit->setToolTip(i18nc("@info:tooltip","Activated by Ctrl+L.")+" "+i18nc("@info:tooltip","Accepts regular expressions")); - connect (m_lineEdit, &QLineEdit::textChanged, this, &CatalogView::setFilterRegExp, Qt::QueuedConnection); + m_lineEdit->setToolTip(i18nc("@info:tooltip", "Activated by Ctrl+L.") + " " + i18nc("@info:tooltip", "Accepts regular expressions")); + connect(m_lineEdit, &QLineEdit::textChanged, this, &CatalogView::setFilterRegExp, Qt::QueuedConnection); // QShortcut* ctrlEsc=new QShortcut(QKeySequence(Qt::META+Qt::Key_Escape),this,SLOT(reset()),0,Qt::WidgetWithChildrenShortcut); - QShortcut* esc=new QShortcut(QKeySequence(Qt::Key_Escape), this, 0, 0, Qt::WidgetWithChildrenShortcut); + QShortcut* esc = new QShortcut(QKeySequence(Qt::Key_Escape), this, 0, 0, Qt::WidgetWithChildrenShortcut); connect(esc, &QShortcut::activated, this, &CatalogView::escaped); - QToolButton* btn=new QToolButton(w); + QToolButton* btn = new QToolButton(w); btn->setPopupMode(QToolButton::InstantPopup); btn->setText(i18n("options")); //btn->setArrowType(Qt::DownArrow); btn->setMenu(new QMenu(this)); - m_filterOptionsMenu=btn->menu(); + m_filterOptionsMenu = btn->menu(); connect(m_filterOptionsMenu, &QMenu::aboutToShow, this, &CatalogView::fillFilterOptionsMenu); connect(m_filterOptionsMenu, &QMenu::triggered, this, &CatalogView::filterOptionToggled); @@ -130,7 +131,7 @@ m_proxyModel->setSourceModel(m_model); m_browser->setModel(m_proxyModel); - m_browser->setColumnWidth(0,m_browser->columnWidth(0)/3); + m_browser->setColumnWidth(0, m_browser->columnWidth(0) / 3); m_browser->setSortingEnabled(true); m_browser->sortByColumn(0, Qt::AscendingOrder); m_browser->setWordWrap(false); @@ -154,34 +155,33 @@ void CatalogView::slotNewEntryDisplayed(const DocPosition& pos) { - QModelIndex item=m_proxyModel->mapFromSource(m_model->index(pos.entry,0)); + QModelIndex item = m_proxyModel->mapFromSource(m_model->index(pos.entry, 0)); m_browser->setCurrentIndex(item); m_browser->scrollTo(item/*,QAbstractItemView::PositionAtCenter*/); } void CatalogView::setFilterRegExp() { - QString expr=m_lineEdit->text(); - if (m_proxyModel->filterRegExp().pattern()!=expr) - m_proxyModel->setFilterRegExp(m_proxyModel->filerOptions()&CatalogTreeFilterModel::IgnoreAccel?expr.remove(Project::instance()->accel()):expr); + QString expr = m_lineEdit->text(); + if (m_proxyModel->filterRegExp().pattern() != expr) + m_proxyModel->setFilterRegExp(m_proxyModel->filerOptions()&CatalogTreeFilterModel::IgnoreAccel ? expr.remove(Project::instance()->accel()) : expr); } void CatalogView::slotItemActivated(const QModelIndex& idx) { - emit gotoEntry(DocPosition(m_proxyModel->mapToSource(idx).row()),0); + emit gotoEntry(DocPosition(m_proxyModel->mapToSource(idx).row()), 0); } void CatalogView::filterOptionToggled(QAction* action) { if (action->data().isNull()) return; - int opt=action->data().toInt(); - if (opt>0) + int opt = action->data().toInt(); + if (opt > 0) m_proxyModel->setFilerOptions(m_proxyModel->filerOptions()^opt); - else - { - if (opt!=-1) opt=-opt-2; + else { + if (opt != -1) opt = -opt - 2; m_proxyModel->setFilterKeyColumn(opt); } m_filterOptionsMenu->clear(); @@ -191,60 +191,58 @@ m_filterOptionsMenu->clear(); if (m_proxyModel->individualRejectFilterEnabled()) - m_filterOptionsMenu->addAction(i18n("Reset individual filter"),this,SLOT(setEntriesFilteredOut())); - - - bool extStates=m_model->catalog()->capabilities()&ExtendedStates; - - const char* const basicTitles[]={ - I18N_NOOP("Case insensitive"), - I18N_NOOP("Ignore accelerator marks"), - I18N_NOOP("Ready"), - I18N_NOOP("Non-ready"), - I18N_NOOP("Non-empty"), - I18N_NOOP("Empty"), - I18N_NOOP("Changed since file open"), - I18N_NOOP("Unchanged since file open"), - I18N_NOOP("Same in sync file"), - I18N_NOOP("Different in sync file"), - I18N_NOOP("Not in sync file"), - I18N_NOOP("Plural"), - I18N_NOOP("Non-plural"), - }; - const char* const* extTitles=Catalog::states(); - const char* const* alltitles[2]={basicTitles,extTitles}; - - QMenu* basicMenu=m_filterOptionsMenu->addMenu(i18nc("@title:inmenu","Basic")); - QMenu* extMenu=extStates?m_filterOptionsMenu->addMenu(i18nc("@title:inmenu","States")):0; - QMenu* allmenus[2]={basicMenu,extMenu}; - QMenu* columnsMenu=m_filterOptionsMenu->addMenu(i18nc("@title:inmenu","Searchable column")); + m_filterOptionsMenu->addAction(i18n("Reset individual filter"), this, SLOT(setEntriesFilteredOut())); + + + bool extStates = m_model->catalog()->capabilities()&ExtendedStates; + + const char* const basicTitles[] = { + I18N_NOOP("Case insensitive"), + I18N_NOOP("Ignore accelerator marks"), + I18N_NOOP("Ready"), + I18N_NOOP("Non-ready"), + I18N_NOOP("Non-empty"), + I18N_NOOP("Empty"), + I18N_NOOP("Changed since file open"), + I18N_NOOP("Unchanged since file open"), + I18N_NOOP("Same in sync file"), + I18N_NOOP("Different in sync file"), + I18N_NOOP("Not in sync file"), + I18N_NOOP("Plural"), + I18N_NOOP("Non-plural"), + }; + const char* const* extTitles = Catalog::states(); + const char* const* alltitles[2] = {basicTitles, extTitles}; + + QMenu* basicMenu = m_filterOptionsMenu->addMenu(i18nc("@title:inmenu", "Basic")); + QMenu* extMenu = extStates ? m_filterOptionsMenu->addMenu(i18nc("@title:inmenu", "States")) : 0; + QMenu* allmenus[2] = {basicMenu, extMenu}; + QMenu* columnsMenu = m_filterOptionsMenu->addMenu(i18nc("@title:inmenu", "Searchable column")); QAction* txt; - txt=m_filterOptionsMenu->addAction(i18nc("@title:inmenu","Resort and refilter on content change"), m_proxyModel, SLOT(setDynamicSortFilter(bool))); + txt = m_filterOptionsMenu->addAction(i18nc("@title:inmenu", "Resort and refilter on content change"), m_proxyModel, SLOT(setDynamicSortFilter(bool))); txt->setCheckable(true); txt->setChecked(m_proxyModel->dynamicSortFilter()); - for (int i=0;(1<=CatalogTreeFilterModel::New; - if (!extStates&&ext) break; - txt=allmenus[ext]->addAction(i18n(alltitles[ext][i-ext*FIRSTSTATEPOSITION])); - txt->setData(1<= CatalogTreeFilterModel::New; + if (!extStates && ext) break; + txt = allmenus[ext]->addAction(i18n(alltitles[ext][i - ext * FIRSTSTATEPOSITION])); + txt->setData(1 << i); txt->setCheckable(true); - txt->setChecked(m_proxyModel->filerOptions()&(1<setChecked(m_proxyModel->filerOptions() & (1 << i)); + if ((1 << i) == CatalogTreeFilterModel::IgnoreAccel) basicMenu->addSeparator(); } if (!extStates) m_filterOptionsMenu->addSeparator(); - for (int i=-1;iaddAction((i==-1)?i18nc("@item:inmenu all columns","All"): - m_model->headerData(i,Qt::Horizontal,Qt::DisplayRole).toString()); - txt->setData(-i-2); + for (int i = -1; i < CatalogTreeModel::DisplayedColumnCount; ++i) { + qCWarning(LOKALIZE_LOG) << i; + txt = columnsMenu->addAction((i == -1) ? i18nc("@item:inmenu all columns", "All") : + m_model->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString()); + txt->setData(-i - 2); txt->setCheckable(true); - txt->setChecked(m_proxyModel->filterKeyColumn()==i); + txt->setChecked(m_proxyModel->filterKeyColumn() == i); } } @@ -264,20 +262,17 @@ int CatalogView::siblingEntryNumber(int step) { - QModelIndex item=m_browser->currentIndex(); - int lastRow=m_proxyModel->rowCount()-1; - if (!item.isValid()) - { - if (lastRow==-1) + QModelIndex item = m_browser->currentIndex(); + int lastRow = m_proxyModel->rowCount() - 1; + if (!item.isValid()) { + if (lastRow == -1) return -1; - item=m_proxyModel->index((step==1)?0:lastRow,0); + item = m_proxyModel->index((step == 1) ? 0 : lastRow, 0); m_browser->setCurrentIndex(item); - } - else - { - if ( item.row() == ((step==-1)?0:lastRow) ) + } else { + if (item.row() == ((step == -1) ? 0 : lastRow)) return -1; - item=item.sibling(item.row()+step,0); + item = item.sibling(item.row() + step, 0); } return m_proxyModel->mapToSource(item).row(); } @@ -297,23 +292,23 @@ if (!m_proxyModel->rowCount()) return -1; - return m_proxyModel->mapToSource(m_proxyModel->index(row,0)).row(); + return m_proxyModel->mapToSource(m_proxyModel->index(row, 0)).row(); } int CatalogView::firstEntryNumber() { - return edgeEntry(m_proxyModel,0); + return edgeEntry(m_proxyModel, 0); } int CatalogView::lastEntryNumber() { - return edgeEntry(m_proxyModel,m_proxyModel->rowCount()-1); + return edgeEntry(m_proxyModel, m_proxyModel->rowCount() - 1); } void CatalogView::setEntryFilteredOut(int entry, bool filteredOut) { - m_proxyModel->setEntryFilteredOut(entry,filteredOut); + m_proxyModel->setEntryFilteredOut(entry, filteredOut); } void CatalogView::setEntriesFilteredOut(bool filteredOut) diff --git a/src/cataloglistview/catalogmodel.h b/src/cataloglistview/catalogmodel.h --- a/src/cataloglistview/catalogmodel.h +++ b/src/cataloglistview/catalogmodel.h @@ -40,12 +40,11 @@ */ class CatalogTreeModel: public QAbstractItemModel { -Q_OBJECT + Q_OBJECT public: - enum CatalogModelColumns - { - Key=0, + enum CatalogModelColumns { + Key = 0, Source, Target, Notes, @@ -56,27 +55,32 @@ IsModified, IsPlural, ColumnCount, - DisplayedColumnCount=TranslationStatus+1 + DisplayedColumnCount = TranslationStatus + 1 }; - enum Roles - { - StringFilterRole=Qt::UserRole+1 + enum Roles { + StringFilterRole = Qt::UserRole + 1 }; CatalogTreeModel(QObject* parent, Catalog* catalog); - ~CatalogTreeModel(){} + ~CatalogTreeModel() {} - QModelIndex index (int row, int column, const QModelIndex& parent=QModelIndex())const; + QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex())const; QModelIndex parent(const QModelIndex&) const; - int rowCount(const QModelIndex& parent=QModelIndex()) const; - int columnCount(const QModelIndex& parent=QModelIndex()) const; - QVariant data(const QModelIndex&,int role=Qt::DisplayRole) const; - QVariant headerData(int section,Qt::Orientation, int role=Qt::DisplayRole) const; + int rowCount(const QModelIndex& parent = QModelIndex()) const; + int columnCount(const QModelIndex& parent = QModelIndex()) const; + QVariant data(const QModelIndex&, int role = Qt::DisplayRole) const; + QVariant headerData(int section, Qt::Orientation, int role = Qt::DisplayRole) const; - Catalog* catalog()const{return m_catalog;} + Catalog* catalog()const + { + return m_catalog; + } - void setIgnoreAccel(bool n){m_ignoreAccel=n;} + void setIgnoreAccel(bool n) + { + m_ignoreAccel = n; + } public slots: void reflectChanges(DocPosition); @@ -98,64 +102,72 @@ class CatalogTreeFilterModel: public QSortFilterProxyModel { -Q_OBJECT + Q_OBJECT public: - enum FilterOptions - { - CaseInsensitive=1<<0, - IgnoreAccel=1<<1, - - Ready=1<<2, - NotReady=1<<3, - NonEmpty=1<<4, - Empty=1<<5, - Modified=1<<6, - NonModified=1<<7, - SameInSync=1<<8, - DifferentInSync=1<<9, - NotInSync=1<<10, - - Plural=1<<11, - NonPlural=1<<12, + enum FilterOptions { + CaseInsensitive = 1 << 0, + IgnoreAccel = 1 << 1, + + Ready = 1 << 2, + NotReady = 1 << 3, + NonEmpty = 1 << 4, + Empty = 1 << 5, + Modified = 1 << 6, + NonModified = 1 << 7, + SameInSync = 1 << 8, + DifferentInSync = 1 << 9, + NotInSync = 1 << 10, + + Plural = 1 << 11, + NonPlural = 1 << 12, //states (see defines below) - New=1<<13, - NeedsTranslation=1<<14, - NeedsL10n=1<<15, - NeedsAdaptation=1<<16, - Translated=1<<17, - NeedsReviewTranslation=1<<18, - NeedsReviewL10n=1<<19, - NeedsReviewAdaptation=1<<20, - Final=1<<21, - SignedOff=1<<22, - MaxOption=1<<23, - AllStates=MaxOption-1 + New = 1 << 13, + NeedsTranslation = 1 << 14, + NeedsL10n = 1 << 15, + NeedsAdaptation = 1 << 16, + Translated = 1 << 17, + NeedsReviewTranslation = 1 << 18, + NeedsReviewL10n = 1 << 19, + NeedsReviewAdaptation = 1 << 20, + Final = 1 << 21, + SignedOff = 1 << 22, + MaxOption = 1 << 23, + AllStates = MaxOption - 1 }; #define STATES ((0xffff<<13)&(AllStates)) #define FIRSTSTATEPOSITION 13 CatalogTreeFilterModel(QObject* parent); - ~CatalogTreeFilterModel(){} + ~CatalogTreeFilterModel() {} bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const; void setFilerOptions(int o); - int filerOptions()const{return m_filerOptions;} + int filerOptions()const + { + return m_filerOptions; + } void setSourceModel(QAbstractItemModel* sourceModel); - bool individualRejectFilterEnabled(){return m_individualRejectFilterEnable;} + bool individualRejectFilterEnabled() + { + return m_individualRejectFilterEnable; + } void setEntryFilteredOut(int entry, bool filteredOut); void setMergeCatalogPointer(MergeCatalog* pointer); public slots: void setEntriesFilteredOut(); void setEntriesFilteredOut(bool filteredOut); - void setDynamicSortFilter(bool enabled){QSortFilterProxyModel::setDynamicSortFilter(enabled);} + void setDynamicSortFilter(bool enabled) + { + QSortFilterProxyModel::setDynamicSortFilter(enabled); + } private: int m_filerOptions; diff --git a/src/cataloglistview/catalogmodel.cpp b/src/cataloglistview/catalogmodel.cpp --- a/src/cataloglistview/catalogmodel.cpp +++ b/src/cataloglistview/catalogmodel.cpp @@ -43,12 +43,11 @@ CatalogTreeModel::CatalogTreeModel(QObject* parent, Catalog* catalog) - : QAbstractItemModel(parent) - , m_catalog(catalog) - , m_ignoreAccel(true) + : QAbstractItemModel(parent) + , m_catalog(catalog) + , m_ignoreAccel(true) { - if (m_fonts.isEmpty()) - { + if (m_fonts.isEmpty()) { QVector fonts(4, QApplication::font()); fonts[1].setItalic(true); //fuzzy @@ -58,13 +57,13 @@ fonts[3].setBold(true); //modified m_fonts.reserve(4); - for(int i=0;i<4;i++) m_fonts<::of(&Catalog::signalFileLoaded), this, &CatalogTreeModel::fileLoaded); } -QModelIndex CatalogTreeModel::index(int row,int column,const QModelIndex& /*parent*/) const +QModelIndex CatalogTreeModel::index(int row, int column, const QModelIndex& /*parent*/) const { return createIndex(row, column); } @@ -88,22 +87,20 @@ void CatalogTreeModel::reflectChanges(DocPosition pos) { - emit dataChanged(index(pos.entry,0),index(pos.entry,DisplayedColumnCount-1)); + emit dataChanged(index(pos.entry, 0), index(pos.entry, DisplayedColumnCount - 1)); #if 0 I disabled dynamicSortFilter function //lazy sorting/filtering - if (rowCount()numberOfEntries()<=index.row() ) + if (m_catalog->numberOfEntries() <= index.row()) return QVariant(); - if (role==Qt::SizeHintRole) - { + if (role == Qt::SizeHintRole) { //no need to cache because of uniform row heights return QFontMetrics(QApplication::font()).size(Qt::TextSingleLine, QString::fromLatin1(" ")); - } - else if (role==Qt::FontRole/* && index.column()==Target*/) - { - bool fuzzy=!m_catalog->isApproved(index.row()); - bool modified=m_catalog->isModified(index.row()); - return m_fonts.at(fuzzy*1 | modified*2); - } - else if (role==Qt::ForegroundRole) - { + } else if (role == Qt::FontRole/* && index.column()==Target*/) { + bool fuzzy = !m_catalog->isApproved(index.row()); + bool modified = m_catalog->isModified(index.row()); + return m_fonts.at(fuzzy * 1 | modified * 2); + } else if (role == Qt::ForegroundRole) { #ifndef NOKDE - if (m_catalog->isBookmarked(index.row())) - { - static KColorScheme colorScheme(QPalette::Normal); - return colorScheme.foreground(KColorScheme::LinkText); - } - if (m_catalog->isObsolete(index.row())) - { - static KColorScheme colorScheme(QPalette::Normal); - return colorScheme.foreground(KColorScheme::InactiveText); - } + if (m_catalog->isBookmarked(index.row())) { + static KColorScheme colorScheme(QPalette::Normal); + return colorScheme.foreground(KColorScheme::LinkText); + } + if (m_catalog->isObsolete(index.row())) { + static KColorScheme colorScheme(QPalette::Normal); + return colorScheme.foreground(KColorScheme::InactiveText); + } #else - if (m_catalog->isBookmarked(index.row())) - { - return QApplication::palette().link(); - } - if (m_catalog->isObsolete(index.row())) - { - return QApplication::palette().brightText(); - } + if (m_catalog->isBookmarked(index.row())) { + return QApplication::palette().link(); + } + if (m_catalog->isObsolete(index.row())) { + return QApplication::palette().brightText(); + } #endif - } - else if (role==Qt::UserRole) - { - switch (index.column()) - { - case TranslationStatus: return m_catalog->isApproved(index.row()); - case IsEmpty: return m_catalog->isEmpty(index.row()); - case State: return int(m_catalog->state(index.row())); - case IsModified: return m_catalog->isModified(index.row()); - case IsPlural: return m_catalog->isPlural(index.row()); - default: role=Qt::DisplayRole; + } else if (role == Qt::UserRole) { + switch (index.column()) { + case TranslationStatus: return m_catalog->isApproved(index.row()); + case IsEmpty: return m_catalog->isEmpty(index.row()); + case State: return int(m_catalog->state(index.row())); + case IsModified: return m_catalog->isModified(index.row()); + case IsPlural: return m_catalog->isPlural(index.row()); + default: role = Qt::DisplayRole; } - } - else if (role==StringFilterRole) //exclude UI strings - { - if (index.column()>=TranslationStatus) + } else if (role == StringFilterRole) { //exclude UI strings + if (index.column() >= TranslationStatus) return QVariant(); - else if (index.column()==Source || index.column()==Target) - { - static const DocPosition::Part parts[]={DocPosition::Source, DocPosition::Target}; - QString str=m_catalog->catalogString(DocPosition(index.row(),parts[index.column()==Target])).string; - return m_ignoreAccel?str.remove(Project::instance()->accel()):str; + else if (index.column() == Source || index.column() == Target) { + static const DocPosition::Part parts[] = {DocPosition::Source, DocPosition::Target}; + QString str = m_catalog->catalogString(DocPosition(index.row(), parts[index.column() == Target])).string; + return m_ignoreAccel ? str.remove(Project::instance()->accel()) : str; } - role=Qt::DisplayRole; + role = Qt::DisplayRole; } - if (role!=Qt::DisplayRole) + if (role != Qt::DisplayRole) return QVariant(); - switch (index.column()) - { - case Key: return index.row()+1; - case Source: return m_catalog->msgid(index.row()); - case Target: return m_catalog->msgstr(index.row()); - case Notes: - { - QString result; - foreach(const Note ¬e, m_catalog->notes(index.row())) - result+=note.content; - return result; - } - case Context: return m_catalog->context(index.row()); - case TranslationStatus: - static QString statuses[]={i18nc("@info:status 'non-fuzzy' in gettext terminology","Ready"), - i18nc("@info:status 'fuzzy' in gettext terminology","Needs review"), - i18nc("@info:status","Untranslated")}; - if (m_catalog->isEmpty(index.row())) - return statuses[2]; - return statuses[!m_catalog->isApproved(index.row())]; + switch (index.column()) { + case Key: return index.row() + 1; + case Source: return m_catalog->msgid(index.row()); + case Target: return m_catalog->msgstr(index.row()); + case Notes: { + QString result; + foreach (const Note ¬e, m_catalog->notes(index.row())) + result += note.content; + return result; + } + case Context: return m_catalog->context(index.row()); + case TranslationStatus: + static QString statuses[] = {i18nc("@info:status 'non-fuzzy' in gettext terminology", "Ready"), + i18nc("@info:status 'fuzzy' in gettext terminology", "Needs review"), + i18nc("@info:status", "Untranslated") + }; + if (m_catalog->isEmpty(index.row())) + return statuses[2]; + return statuses[!m_catalog->isApproved(index.row())]; } return QVariant(); } CatalogTreeFilterModel::CatalogTreeFilterModel(QObject* parent) - : QSortFilterProxyModel(parent) - , m_filerOptions(AllStates) - , m_individualRejectFilterEnable(false) - , m_mergeCatalog(NULL) + : QSortFilterProxyModel(parent) + , m_filerOptions(AllStates) + , m_individualRejectFilterEnable(false) + , m_mergeCatalog(NULL) { setFilterKeyColumn(-1); setFilterCaseSensitivity(Qt::CaseInsensitive); @@ -250,50 +230,46 @@ void CatalogTreeFilterModel::setEntriesFilteredOut(bool filteredOut) { m_individualRejectFilter.fill(filteredOut, sourceModel()->rowCount()); - m_individualRejectFilterEnable=filteredOut; + m_individualRejectFilterEnable = filteredOut; invalidateFilter(); } void CatalogTreeFilterModel::setEntryFilteredOut(int entry, bool filteredOut) { // if (entry>=m_individualRejectFilter.size()) // sourceModelReset(); - m_individualRejectFilter[entry]=filteredOut; - m_individualRejectFilterEnable=true; + m_individualRejectFilter[entry] = filteredOut; + m_individualRejectFilterEnable = true; invalidateFilter(); } void CatalogTreeFilterModel::setFilerOptions(int o) { - m_filerOptions=o; - setFilterCaseSensitivity(o&CaseInsensitive?Qt::CaseInsensitive:Qt::CaseSensitive); - static_cast(sourceModel())->setIgnoreAccel(o&IgnoreAccel); + m_filerOptions = o; + setFilterCaseSensitivity(o & CaseInsensitive ? Qt::CaseInsensitive : Qt::CaseSensitive); + static_cast(sourceModel())->setIgnoreAccel(o & IgnoreAccel); invalidateFilter(); } bool CatalogTreeFilterModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const { - int filerOptions=m_filerOptions; - bool accepts=true; - if (bool(filerOptions&Ready)!=bool(filerOptions&NotReady)) - { - bool ready=sourceModel()->index(source_row,CatalogTreeModel::TranslationStatus,source_parent).data(Qt::UserRole).toBool(); - accepts=(ready==bool(filerOptions&Ready) || ready!=bool(filerOptions&NotReady)); + int filerOptions = m_filerOptions; + bool accepts = true; + if (bool(filerOptions & Ready) != bool(filerOptions & NotReady)) { + bool ready = sourceModel()->index(source_row, CatalogTreeModel::TranslationStatus, source_parent).data(Qt::UserRole).toBool(); + accepts = (ready == bool(filerOptions & Ready) || ready != bool(filerOptions & NotReady)); } - if (accepts&&bool(filerOptions&NonEmpty)!=bool(filerOptions&Empty)) - { - bool untr=sourceModel()->index(source_row,CatalogTreeModel::IsEmpty,source_parent).data(Qt::UserRole).toBool(); - accepts=(untr==bool(filerOptions&Empty) || untr!=bool(filerOptions&NonEmpty)); + if (accepts && bool(filerOptions & NonEmpty) != bool(filerOptions & Empty)) { + bool untr = sourceModel()->index(source_row, CatalogTreeModel::IsEmpty, source_parent).data(Qt::UserRole).toBool(); + accepts = (untr == bool(filerOptions & Empty) || untr != bool(filerOptions & NonEmpty)); } - if (accepts&&bool(filerOptions&Modified)!=bool(filerOptions&NonModified)) - { - bool modified=sourceModel()->index(source_row,CatalogTreeModel::IsModified,source_parent).data(Qt::UserRole).toBool(); - accepts=(modified==bool(filerOptions&Modified) || modified!=bool(filerOptions&NonModified)); + if (accepts && bool(filerOptions & Modified) != bool(filerOptions & NonModified)) { + bool modified = sourceModel()->index(source_row, CatalogTreeModel::IsModified, source_parent).data(Qt::UserRole).toBool(); + accepts = (modified == bool(filerOptions & Modified) || modified != bool(filerOptions & NonModified)); } - if (accepts&&bool(filerOptions&Plural)!=bool(filerOptions&NonPlural)) - { - bool modified=sourceModel()->index(source_row,CatalogTreeModel::IsPlural,source_parent).data(Qt::UserRole).toBool(); - accepts=(modified==bool(filerOptions&Plural) || modified!=bool(filerOptions&NonPlural)); + if (accepts && bool(filerOptions & Plural) != bool(filerOptions & NonPlural)) { + bool modified = sourceModel()->index(source_row, CatalogTreeModel::IsPlural, source_parent).data(Qt::UserRole).toBool(); + accepts = (modified == bool(filerOptions & Plural) || modified != bool(filerOptions & NonPlural)); } // These are the possible sync options of a row: @@ -303,28 +279,26 @@ // // The code below takes care of filtering rows when any of those options is not checked. // - const int mask=(SameInSync|DifferentInSync|NotInSync); - if (accepts && m_mergeCatalog && (filerOptions&mask) && (filerOptions&mask)!=mask) - { + const int mask = (SameInSync | DifferentInSync | NotInSync); + if (accepts && m_mergeCatalog && (filerOptions & mask) && (filerOptions & mask) != mask) { bool isPresent = m_mergeCatalog->isPresent(source_row); bool isDifferent = m_mergeCatalog->isDifferent(source_row); accepts = ! - ( (isPresent && !isDifferent && !bool(filerOptions&SameInSync)) || - (isPresent && isDifferent && !bool(filerOptions&DifferentInSync)) || - (!isPresent && !bool(filerOptions&NotInSync)) - ); + ((isPresent && !isDifferent && !bool(filerOptions & SameInSync)) || + (isPresent && isDifferent && !bool(filerOptions & DifferentInSync)) || + (!isPresent && !bool(filerOptions & NotInSync)) + ); } - if (accepts && (filerOptions&STATES)!=STATES) - { - int state=sourceModel()->index(source_row,CatalogTreeModel::State,source_parent).data(Qt::UserRole).toInt(); - accepts=(filerOptions&(1<<(state+FIRSTSTATEPOSITION))); + if (accepts && (filerOptions & STATES) != STATES) { + int state = sourceModel()->index(source_row, CatalogTreeModel::State, source_parent).data(Qt::UserRole).toInt(); + accepts = (filerOptions & (1 << (state + FIRSTSTATEPOSITION))); } - accepts=accepts&&!(m_individualRejectFilterEnable && source_row */ -enum {Html=1}; +enum {Html = 1}; QString userVisibleWordDiff(const QString& oldString, - const QString& newString, - const QString& accelRx, - const QString& markupRx, - int options=0); + const QString& newString, + const QString& accelRx, + const QString& markupRx, + int options = 0); diff --git a/src/common/diff.cpp b/src/common/diff.cpp --- a/src/common/diff.cpp +++ b/src/common/diff.cpp @@ -37,19 +37,18 @@ #include -typedef enum -{ +typedef enum { NOTHING = 0, ARROW_UP = 1, ARROW_LEFT = 2, ARROW_UP_LEFT = 3, FINAL = 4 } LCSMarker; -static const QString addMarkerStart=QStringLiteral(""); -static const QString addMarkerEnd=QStringLiteral(""); -static const QString delMarkerStart=QStringLiteral(""); -static const QString delMarkerEnd=QStringLiteral(""); +static const QString addMarkerStart = QStringLiteral(""); +static const QString addMarkerEnd = QStringLiteral(""); +static const QString delMarkerStart = QStringLiteral(""); +static const QString delMarkerEnd = QStringLiteral(""); QStringList calcLCS(const QStringList& s1Words, const QStringList& s2Words, @@ -64,39 +63,39 @@ * @short Class for keeping "global" params of recursive function * @author Nick Shaforostoff */ - class LCSprinter +class LCSprinter { - public: - LCSprinter(const QStringList &s_1, - const QStringList& s_2, - QVector *b_, - const uint nT_, - uint index, - const QStringList& s1Space_, - const QStringList& s2Space_ - ); - ~LCSprinter() {}; - void printLCS(uint index); - inline QStringList operator()(); - - private: - QStringList s1, s2; - QLinkedList resultString; - QStringList s1Space, s2Space; - QStringList::const_iterator it1, it2; - QStringList::const_iterator it1Space, it2Space; - uint nT:31;//we're using 1d vector as 2d - bool haveSpaces:1;//"word: sfdfs" space is ": " - QVector *b; - //QStringList::iterator it1Space, it2Space; +public: + LCSprinter(const QStringList &s_1, + const QStringList& s_2, + QVector *b_, + const uint nT_, + uint index, + const QStringList& s1Space_, + const QStringList& s2Space_ + ); + ~LCSprinter() {}; + void printLCS(uint index); + inline QStringList operator()(); + +private: + QStringList s1, s2; + QLinkedList resultString; + QStringList s1Space, s2Space; + QStringList::const_iterator it1, it2; + QStringList::const_iterator it1Space, it2Space; + uint nT: 31; //we're using 1d vector as 2d + bool haveSpaces: 1; //"word: sfdfs" space is ": " + QVector *b; + //QStringList::iterator it1Space, it2Space; }; inline QStringList LCSprinter::operator()() { QStringList result; - foreach(const QString& str, resultString) - result<=0) + int i = str.size(); + while (--i >= 0) result.prepend(QString(str.at(i))); result.prepend(QString()); return result; } void LCSprinter::printLCS(uint index) { //fprintf(stderr,"%2d. %2d. %2d. %2d\n",(uint)(*b)[index],nT,index%nT, index); - if (index % nT == 0 || index < nT) - { - // original LCS algo does not have to deal with ins before first common - uint bound = index%nT; - for (index=0; indexat(index)) - { - printLCS(index-nT-1); - if (it1!=s1.constEnd()) - { + if (ARROW_UP_LEFT == b->at(index)) { + printLCS(index - nT - 1); + if (it1 != s1.constEnd()) { //qCWarning(LOKALIZE_LOG) << "upleft '" << *it1 <<"'"; //qCWarning(LOKALIZE_LOG) << "upleft 1s" << *it1Space; //qCWarning(LOKALIZE_LOG) << "upleft 2s" << *it2Space; - if (haveSpaces) - { - if((*it1)==(*it2))//case and accels + if (haveSpaces) { + if ((*it1) == (*it2)) //case and accels resultString.append(*it1); - else - { - QStringList word1=prepareForInternalDiff(*it1); - QStringList word2=prepareForInternalDiff(*it2); + else { + QStringList word1 = prepareForInternalDiff(*it1); + QStringList word2 = prepareForInternalDiff(*it2); QStringList empty; - resultString.append(calcLCS(word1,word2,empty,empty).join(QString())); + resultString.append(calcLCS(word1, word2, empty, empty).join(QString())); } - if((*it1Space)==(*it2Space)) + if ((*it1Space) == (*it2Space)) resultString.append(*it1Space); - else - { - QStringList word1=prepareForInternalDiff(*it1Space); - QStringList word2=prepareForInternalDiff(*it2Space); + else { + QStringList word1 = prepareForInternalDiff(*it1Space); + QStringList word2 = prepareForInternalDiff(*it2Space); QStringList empty; //empty=calcLCS(word1,word2,empty,empty); //???this is not really good if we use diff result in autosubst - empty=calcLCS(word2,word1,empty,empty); - empty.replaceInStrings(QStringLiteral("KBABELADD>"),QStringLiteral("KBABELTMP>")); - empty.replaceInStrings(QStringLiteral("KBABELDEL>"),QStringLiteral("KBABELADD>")); - empty.replaceInStrings(QStringLiteral("KBABELTMP>"),QStringLiteral("KBABELDEL>")); + empty = calcLCS(word2, word1, empty, empty); + empty.replaceInStrings(QStringLiteral("KBABELADD>"), QStringLiteral("KBABELTMP>")); + empty.replaceInStrings(QStringLiteral("KBABELDEL>"), QStringLiteral("KBABELADD>")); + empty.replaceInStrings(QStringLiteral("KBABELTMP>"), QStringLiteral("KBABELDEL>")); resultString.append(empty.join(QString())); } ++it1Space; ++it2Space; //qCWarning(LOKALIZE_LOG) << " common " << *it1; - } - else + } else resultString.append(*it1);//we may guess that this is a batch job, i.e. TM search ++it1; ++it2; } - } - else if (ARROW_UP == b->at(index)) - { - printLCS(index-nT); + } else if (ARROW_UP == b->at(index)) { + printLCS(index - nT); // if (it1!=s1.end()) { //qCWarning(LOKALIZE_LOG)<<"APPENDDEL "<<*it1; //qCWarning(LOKALIZE_LOG)<<"APPENDDEL "<<*it1Space; resultString.append(delMarkerStart); resultString.append(*it1); ++it1; - if (haveSpaces) - { + if (haveSpaces) { resultString.append(*it1Space); ++it1Space; } resultString.append(delMarkerEnd); } - } - else - { - printLCS(index-1); + } else { + printLCS(index - 1); resultString.append(addMarkerStart); resultString.append(*it2); ++it2; - if (haveSpaces) - { + if (haveSpaces) { //qCWarning(LOKALIZE_LOG) << "add2 " << *it2; resultString.append(*it2Space); ++it2Space; @@ -266,66 +250,56 @@ QStringList s1(s1Words); QStringList s2(s2Words); - if (!s1Space.isEmpty()) - { + if (!s1Space.isEmpty()) { //accels are only removed by batch jobs //and this is not the one //also, lower things a bit :) - for (i=0;iaccel()); - i=mX; - while(--i>0) - { - if ((s1Space.at(i)==accel)) - { - s1[i]+=s1[i+1]; - s1.removeAt(i+1); + i = mX; + while (--i > 0) { + if ((s1Space.at(i) == accel)) { + s1[i] += s1[i + 1]; + s1.removeAt(i + 1); s1Space.removeAt(i); - s1Words[i]+=s1[i+1]; - s1Words.removeAt(i+1); + s1Words[i] += s1[i + 1]; + s1Words.removeAt(i + 1); --mX; --nY; } } #endif } - uint mT = mX+1; - uint nT = nY+1; + uint mT = mX + 1; + uint nT = nY + 1; - QVector b(mT*nT, NOTHING); - QVector c(mT*nT, 0); + QVector b(mT * nT, NOTHING); + QVector c(mT * nT, 0); b[0] = FINAL; uint index_cache = 0; QStringList::const_iterator it1, it2; - for (i=1, it1 = s1.constBegin(); i= c.at(index_cache-1)) - { - c[index_cache] = c.at(index_cache-nT); + } else if (c.at(index_cache - nT) >= c.at(index_cache - 1)) { + c[index_cache] = c.at(index_cache - nT); b[index_cache] = ARROW_UP; - } - else - { - c[index_cache] = c.at(index_cache-1); + } else { + c[index_cache] = c.at(index_cache - 1); b[index_cache] = ARROW_LEFT; } } @@ -346,18 +320,18 @@ s2.prepend(space); static QStringList empty; - QStringList list=calcLCS(s1,s2,empty,empty); - bool r=list.first()==space; + QStringList list = calcLCS(s1, s2, empty, empty); + bool r = list.first() == space; if (r) list.removeFirst(); else - qCDebug(LOKALIZE_LOG)<<"first ' ' assumption is wrong"<")); result.remove(QStringLiteral("")); @@ -369,37 +343,35 @@ static void prepareLists(QString str, QStringList& main, QStringList& space, const QString& accel, QString markup) { Q_UNUSED(accel); - int pos=0; + int pos = 0; //accels are only removed by batch jobs //and this is not the one #if 0 - QRegExp rxAccelInWord("[^\\W|\\d]"+accel+"[^\\W|\\d]"); - int accelLen=accel.size(); - while ((pos=rxAccelInWord.indexIn(str,pos))!=-1) - { - str.remove(rxAccelInWord.pos()+1,accelLen); - pos+=2;//two letters + QRegExp rxAccelInWord("[^\\W|\\d]" + accel + "[^\\W|\\d]"); + int accelLen = accel.size(); + while ((pos = rxAccelInWord.indexIn(str, pos)) != -1) { + str.remove(rxAccelInWord.pos() + 1, accelLen); + pos += 2; //two letters } #endif //QRegExp rxSplit("\\W+|\\d+"); //i tried that but it failed: if (!markup.isEmpty()) - markup+='|'; - QRegExp rxSplit('('%markup%QLatin1String("\\W+|\\d+)+")); + markup += '|'; + QRegExp rxSplit('(' % markup % QLatin1String("\\W+|\\d+)+")); - main=str.split(rxSplit,QString::SkipEmptyParts); + main = str.split(rxSplit, QString::SkipEmptyParts); main.prepend("\t");//little hack //ensure the string always begins with the space part str.prepend('\b'); - pos=0; - while ((pos=rxSplit.indexIn(str,pos))!=-1) - { + pos = 0; + while ((pos = rxSplit.indexIn(str, pos)) != -1) { space.append(rxSplit.cap(0)); - pos+=rxSplit.matchedLength(); + pos += rxSplit.matchedLength(); } space.append(QString());//so we don't have to worry about list boundaries space.append(QString());//so we don't have to worry about list boundaries @@ -425,23 +397,22 @@ //QStringList s2Space(str2ForMatching.split(rxSpace,QString::SkipEmptyParts)); - QStringList result(calcLCS(s1,s2,s1Space,s2Space)); + QStringList result(calcLCS(s1, s2, s1Space, s2Space)); result.removeFirst();//\t - result.first().remove(0,1);//\b + result.first().remove(0, 1); //\b // qCWarning(LOKALIZE_LOG)<<"wordDiff 1 '" <"),QString()); - result.replaceInStrings(QStringLiteral(""),QString()); - - result.replaceInStrings(QStringLiteral(""),QStringLiteral("{KBABELADD}")); - result.replaceInStrings(QStringLiteral(""),QStringLiteral("{/KBABELADD}")); - result.replaceInStrings(QStringLiteral(""),QStringLiteral("{KBABELDEL}")); - result.replaceInStrings(QStringLiteral(""),QStringLiteral("{/KBABELDEL}")); - - if (options&Html) - { - result.replaceInStrings(QStringLiteral("&"),QStringLiteral("&")); - result.replaceInStrings(QStringLiteral("<"),QStringLiteral("<")); - result.replaceInStrings(QStringLiteral(">"),QStringLiteral(">")); + result.replaceInStrings(QStringLiteral(""), QString()); + result.replaceInStrings(QStringLiteral(""), QString()); + + result.replaceInStrings(QStringLiteral(""), QStringLiteral("{KBABELADD}")); + result.replaceInStrings(QStringLiteral(""), QStringLiteral("{/KBABELADD}")); + result.replaceInStrings(QStringLiteral(""), QStringLiteral("{KBABELDEL}")); + result.replaceInStrings(QStringLiteral(""), QStringLiteral("{/KBABELDEL}")); + + if (options & Html) { + result.replaceInStrings(QStringLiteral("&"), QStringLiteral("&")); + result.replaceInStrings(QStringLiteral("<"), QStringLiteral("<")); + result.replaceInStrings(QStringLiteral(">"), QStringLiteral(">")); } //result.last().chop(1);//\b @@ -451,13 +422,12 @@ res.remove(QStringLiteral("{/KBABELADD}{KBABELADD}")); res.remove(QStringLiteral("{/KBABELDEL}{KBABELDEL}")); - if (options&Html) - { - res.replace(QLatin1String("{KBABELADD}"),QLatin1String("")); - res.replace(QLatin1String("{/KBABELADD}"),QLatin1String("")); - res.replace(QLatin1String("{KBABELDEL}"),QLatin1String("")); - res.replace(QLatin1String("{/KBABELDEL}"),QLatin1String("")); - res.replace(QLatin1String("\\n"),QLatin1String("\\n
")); + if (options & Html) { + res.replace(QLatin1String("{KBABELADD}"), QLatin1String("")); + res.replace(QLatin1String("{/KBABELADD}"), QLatin1String("")); + res.replace(QLatin1String("{KBABELDEL}"), QLatin1String("")); + res.replace(QLatin1String("{/KBABELDEL}"), QLatin1String("")); + res.replace(QLatin1String("\\n"), QLatin1String("\\n
")); } return res; diff --git a/src/common/domroutines.h b/src/common/domroutines.h --- a/src/common/domroutines.h +++ b/src/common/domroutines.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, diff --git a/src/common/domroutines.cpp b/src/common/domroutines.cpp --- a/src/common/domroutines.cpp +++ b/src/common/domroutines.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -25,17 +25,15 @@ void setText(QDomElement element, QString text) { - QDomNodeList children=element.childNodes(); - for (int i=0;i #endif -QString convertToHtml(QString string, bool italics=false); +QString convertToHtml(QString string, bool italics = false); /** * remember to connect appropriate signals to reset slot * for delegate to have actual cache - * + * * @author Nick Shaforostoff */ class FastSizeHintItemDelegate: public QItemDelegate { - Q_OBJECT + Q_OBJECT public: - enum Roles - { - HtmlDisplayRole=Qt::UserRole+5 + enum Roles { + HtmlDisplayRole = Qt::UserRole + 5 }; FastSizeHintItemDelegate(QObject *parent, const QVector& slc, const QVector& rtc); - ~FastSizeHintItemDelegate(){} + ~FastSizeHintItemDelegate() {} void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; @@ -64,13 +63,11 @@ QVector singleLineColumns; QVector richTextColumns; - struct RowColumn - { - short row:16; - short column:16; + struct RowColumn { + short row: 16; + short column: 16; }; - union RowColumnUnion - { + union RowColumnUnion { RowColumn index; int v; }; diff --git a/src/common/fastsizehintitemdelegate.cpp b/src/common/fastsizehintitemdelegate.cpp --- a/src/common/fastsizehintitemdelegate.cpp +++ b/src/common/fastsizehintitemdelegate.cpp @@ -45,20 +45,19 @@ QSize FastSizeHintItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { - int lineCount=1; - int nPos=20; - int column=qMax(index.column(),0); - if (!singleLineColumns.at(column)) - { - QString text=index.data().toString(); - nPos=text.indexOf('\n'); - if (nPos==-1) - nPos=text.size(); + int lineCount = 1; + int nPos = 20; + int column = qMax(index.column(), 0); + if (!singleLineColumns.at(column)) { + QString text = index.data().toString(); + nPos = text.indexOf('\n'); + if (nPos == -1) + nPos = text.size(); else - lineCount+=text.count('\n'); + lineCount += text.count('\n'); } static QFontMetrics metrics(option.font); - return QSize(metrics.averageCharWidth()*nPos, metrics.height()*lineCount); + return QSize(metrics.averageCharWidth() * nPos, metrics.height() * lineCount); } void FastSizeHintItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const @@ -69,59 +68,56 @@ painter->setClipRect(option.rect); QBrush bgBrush; #ifndef NOKDE - const KColorScheme& scheme=activeScheme; - if (option.state&QStyle::State_MouseOver) - bgBrush=scheme.background(KColorScheme::LinkBackground); - else if (index.row()%2) - bgBrush=scheme.background(KColorScheme::AlternateBackground); + const KColorScheme& scheme = activeScheme; + if (option.state & QStyle::State_MouseOver) + bgBrush = scheme.background(KColorScheme::LinkBackground); + else if (index.row() % 2) + bgBrush = scheme.background(KColorScheme::AlternateBackground); else - bgBrush=scheme.background(KColorScheme::NormalBackground); + bgBrush = scheme.background(KColorScheme::NormalBackground); #else static QPalette p; - if (option.state&QStyle::State_MouseOver) - bgBrush=p.highlight(); - else if (index.row()%2) - bgBrush=p.alternateBase(); + if (option.state & QStyle::State_MouseOver) + bgBrush = p.highlight(); + else if (index.row() % 2) + bgBrush = p.alternateBase(); else - bgBrush=p.base(); + bgBrush = p.base(); #endif - + painter->fillRect(option.rect, bgBrush); - painter->setClipRect(option.rect.adjusted(0,0,-2,0)); + painter->setClipRect(option.rect.adjusted(0, 0, -2, 0)); //painter->setFont(option.font); RowColumnUnion rc; - rc.index.row=index.row(); - rc.index.column=index.column(); + rc.index.row = index.row(); + rc.index.column = index.column(); //TMDBModel* m=static_cast(index.model()); - if (!cache.contains(rc.v)) - { - QString text=index.data(FastSizeHintItemDelegate::HtmlDisplayRole).toString(); + if (!cache.contains(rc.v)) { + QString text = index.data(FastSizeHintItemDelegate::HtmlDisplayRole).toString(); cache.insert(rc.v, new QStaticText(text)); - cache.object(rc.v)->setTextFormat(richTextColumns.at(index.column())?Qt::RichText:Qt::PlainText); + cache.object(rc.v)->setTextFormat(richTextColumns.at(index.column()) ? Qt::RichText : Qt::PlainText); } - int rectWidth=option.rect.width(); - QStaticText* staticText=cache.object(rc.v); + int rectWidth = option.rect.width(); + QStaticText* staticText = cache.object(rc.v); //staticText->setTextWidth(rectWidth-4); - QPoint textStartPoint=option.rect.topLeft(); - textStartPoint.rx()+=2; + QPoint textStartPoint = option.rect.topLeft(); + textStartPoint.rx() += 2; painter->drawStaticText(textStartPoint, *staticText); - if (staticText->size().width()<=rectWidth-4) - { + if (staticText->size().width() <= rectWidth - 4) { painter->restore(); return; } painter->setPen(bgBrush.color()); - QPoint p1=option.rect.topRight(); - QPoint p2=option.rect.bottomRight(); - int limit=qMin(8, rectWidth-2); - int i=limit; - while(--i>0) - { - painter->setOpacity(float(i)/limit); + QPoint p1 = option.rect.topRight(); + QPoint p2 = option.rect.bottomRight(); + int limit = qMin(8, rectWidth - 2); + int i = limit; + while (--i > 0) { + painter->setOpacity(float(i) / limit); painter->drawLine(p1, p2); p1.rx()--; p2.rx()--; @@ -131,15 +127,15 @@ QString convertToHtml(QString str, bool italics) { -/* - if (str.isEmpty()) - return str; -*/ + /* + if (str.isEmpty()) + return str; + */ - str=Qt::convertFromPlainText(str); //FIXME use another routine (this has bugs) + str = Qt::convertFromPlainText(str); //FIXME use another routine (this has bugs) if (italics) - str="

" % QString::fromRawData(str.unicode()+3, str.length()-3-4) % "

"; + str = "

" % QString::fromRawData(str.unicode() + 3, str.length() - 3 - 4) % "

"; return str; } diff --git a/src/common/flowlayout.h b/src/common/flowlayout.h --- a/src/common/flowlayout.h +++ b/src/common/flowlayout.h @@ -48,18 +48,17 @@ { public: - enum User - { + enum User { glossary, webquery, standard }; /** * c'tor for glossary view */ - FlowLayout(User user=standard, QWidget *signalingWidget = 0, - const QVector& actions=QVector(), int margin = 0, int spacing = -1); + FlowLayout(User user = standard, QWidget *signalingWidget = 0, + const QVector& actions = QVector(), int margin = 0, int spacing = -1); ~FlowLayout(); @@ -78,7 +77,7 @@ * @param term is the term matched * @param entry is index of entry in the Glossary list */ - void addTerm(const QString& term, const QByteArray& entryId, bool capFirst=false); + void addTerm(const QString& term, const QByteArray& entryId, bool capFirst = false); void clearTerms(); private: diff --git a/src/common/flowlayout.cpp b/src/common/flowlayout.cpp --- a/src/common/flowlayout.cpp +++ b/src/common/flowlayout.cpp @@ -48,19 +48,17 @@ const QVector& actions, int margin, int spacing) - : QLayout() - , m_index(0) - , m_receiver(signalingWidget) + : QLayout() + , m_index(0) + , m_receiver(signalingWidget) { setSizeConstraint(QLayout::SetMinAndMaxSize); setMargin(margin); setSpacing(spacing); - if (user==glossary) - { - foreach (QAction* action, actions) - { - TermLabel* label=new TermLabel(action); /*this,m_keys.at(count())*/ + if (user == glossary) { + foreach (QAction* action, actions) { + TermLabel* label = new TermLabel(action); /*this,m_keys.at(count())*/ connect(action, &QAction::triggered, label, &GlossaryNS::TermLabel::insert); connect(label, &GlossaryNS::TermLabel::insertTerm, (GlossaryNS::GlossaryView*)m_receiver, &GlossaryNS::GlossaryView::termInsertRequested); label->hide(); @@ -86,7 +84,7 @@ // m_keys.append((Qt::Key)i); // } // } -// +// // } } @@ -112,10 +110,22 @@ return itemList.value(index); } -void FlowLayout::addItem(QLayoutItem *item) {itemList.append(item);} -int FlowLayout::count() const {return itemList.size();} -Qt::Orientations FlowLayout::expandingDirections() const {return 0;} -bool FlowLayout::hasHeightForWidth() const {return true;} +void FlowLayout::addItem(QLayoutItem *item) +{ + itemList.append(item); +} +int FlowLayout::count() const +{ + return itemList.size(); +} +Qt::Orientations FlowLayout::expandingDirections() const +{ + return 0; +} +bool FlowLayout::hasHeightForWidth() const +{ + return true; +} int FlowLayout::heightForWidth(int width) const { @@ -140,7 +150,7 @@ foreach (QLayoutItem* item, itemList) size = size.expandedTo(item->minimumSize()); - size += QSize(2*margin(), 2*margin()); + size += QSize(2 * margin(), 2 * margin()); return size; } @@ -150,11 +160,9 @@ int y = rect.y(); int lineHeight = 0; - foreach (QLayoutItem* item, itemList) - { + foreach (QLayoutItem* item, itemList) { int nextX = x + item->sizeHint().width() + spacing(); - if (nextX - spacing() > rect.right() && lineHeight > 0) - { + if (nextX - spacing() > rect.right() && lineHeight > 0) { x = rect.x(); y = y + lineHeight + spacing(); nextX = x + item->sizeHint().width() + spacing(); @@ -175,20 +183,19 @@ setEnabled(false); foreach (QLayoutItem* item, itemList) static_cast(item->widget())->hide(); - m_index=0; + m_index = 0; setEnabled(true); } void FlowLayout::addTerm(const QString& term, const QByteArray& entryId, bool capFirst) { //fill layout with labels - while (m_index>=count()) - { - TermLabel* label=new TermLabel; + while (m_index >= count()) { + TermLabel* label = new TermLabel; connect(label, &TermLabel::insertTerm, (GlossaryNS::GlossaryView*)m_receiver, &GlossaryNS::GlossaryView::termInsertRequested); addWidget(label); } - TermLabel* label=static_cast(itemAt(m_index)->widget()); + TermLabel* label = static_cast(itemAt(m_index)->widget()); label->setText(term, entryId, capFirst); label->show(); ++m_index; diff --git a/src/common/headerviewmenu.h b/src/common/headerviewmenu.h --- a/src/common/headerviewmenu.h +++ b/src/common/headerviewmenu.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, diff --git a/src/common/headerviewmenu.cpp b/src/common/headerviewmenu.cpp --- a/src/common/headerviewmenu.cpp +++ b/src/common/headerviewmenu.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -38,9 +38,8 @@ QMenu* headerMenu = new QMenu(headerView); connect(headerMenu, &QMenu::aboutToHide, headerMenu, &QMenu::deleteLater, Qt::QueuedConnection); connect(headerMenu, &QMenu::triggered, this, &HeaderViewMenuHandler::headerMenuActionToggled); - for (int i=0;icount();++i) - { - QAction* a=headerMenu->addAction(headerView->model()->headerData(i,Qt::Horizontal,Qt::DisplayRole).toString()); + for (int i = 0; i < headerView->count(); ++i) { + QAction* a = headerMenu->addAction(headerView->model()->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString()); a->setData(i); a->setCheckable(true); a->setChecked(!headerView->isSectionHidden(i)); diff --git a/src/common/htmlhelpers.cpp b/src/common/htmlhelpers.cpp --- a/src/common/htmlhelpers.cpp +++ b/src/common/htmlhelpers.cpp @@ -29,16 +29,15 @@ { QString html; static QRegularExpression urlDetector(QStringLiteral("(https?|ftp)://[^\\s/$.?#].[^\\s]*")); - QStringList parts=text.split(urlDetector); - if (parts.size()) html+=parts.takeFirst().toHtmlEscaped(); + QStringList parts = text.split(urlDetector); + if (parts.size()) html += parts.takeFirst().toHtmlEscaped(); QRegularExpressionMatchIterator i = urlDetector.globalMatch(text); - while (i.hasNext()) - { + while (i.hasNext()) { QRegularExpressionMatch match = i.next(); QString word = match.captured(0); - html+=QStringLiteral("")%word.toHtmlEscaped()%QStringLiteral(""); - if (parts.size()) html+=parts.takeFirst().toHtmlEscaped(); + html += QStringLiteral("") % word.toHtmlEscaped() % QStringLiteral(""); + if (parts.size()) html += parts.takeFirst().toHtmlEscaped(); } return html; } diff --git a/src/common/languagelistmodel.h b/src/common/languagelistmodel.h --- a/src/common/languagelistmodel.h +++ b/src/common/languagelistmodel.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -31,8 +31,7 @@ class LanguageListModel: public QStringListModel { - enum ModelType - { + enum ModelType { Default, WithEmptyLang }; @@ -45,25 +44,28 @@ static LanguageListModel * _emptyLangInstance; static void cleanupLanguageListModel(); - LanguageListModel(ModelType type=Default, QObject* parent=0); + LanguageListModel(ModelType type = Default, QObject* parent = 0); QSortFilterProxyModel* m_sortModel; KConfig* m_systemLangList; public: QVariant data(const QModelIndex& index, int role) const; QFlags< Qt::ItemFlag > flags(const QModelIndex& index) const; - QSortFilterProxyModel* sortModel() const{return m_sortModel;}; + QSortFilterProxyModel* sortModel() const + { + return m_sortModel; + }; int sortModelRowForLangCode(const QString&); QString langCodeForSortModelRow(int); }; -QString getTargetLangCode(const QString& title, bool askUser = +QString getTargetLangCode(const QString& title, bool askUser = #ifndef NOKDE -false + false #else -true + true #endif -); + ); #endif // LANGUAGELISTMODEL_H diff --git a/src/common/languagelistmodel.cpp b/src/common/languagelistmodel.cpp --- a/src/common/languagelistmodel.cpp +++ b/src/common/languagelistmodel.cpp @@ -39,50 +39,49 @@ -LanguageListModel* LanguageListModel::_instance=0; -LanguageListModel* LanguageListModel::_emptyLangInstance=0; +LanguageListModel* LanguageListModel::_instance = 0; +LanguageListModel* LanguageListModel::_emptyLangInstance = 0; void LanguageListModel::cleanupLanguageListModel() { delete LanguageListModel::_instance; LanguageListModel::_instance = 0; delete LanguageListModel::_emptyLangInstance; LanguageListModel::_emptyLangInstance = 0; } LanguageListModel* LanguageListModel::instance() { - if (_instance==0 ) - { - _instance=new LanguageListModel(); + if (_instance == 0) { + _instance = new LanguageListModel(); qAddPostRoutine(LanguageListModel::cleanupLanguageListModel); } return _instance; } LanguageListModel* LanguageListModel::emptyLangInstance() { - if (_emptyLangInstance==0 ) - _emptyLangInstance=new LanguageListModel(WithEmptyLang); + if (_emptyLangInstance == 0) + _emptyLangInstance = new LanguageListModel(WithEmptyLang); return _emptyLangInstance; } LanguageListModel::LanguageListModel(ModelType type, QObject* parent) - : QStringListModel(parent) - , m_sortModel(new QSortFilterProxyModel(this)) + : QStringListModel(parent) + , m_sortModel(new QSortFilterProxyModel(this)) #ifndef NOKDE - , m_systemLangList(new KConfig(QLatin1String("locale/kf5_all_languages"), KConfig::NoGlobals, QStandardPaths::GenericDataLocation)) + , m_systemLangList(new KConfig(QLatin1String("locale/kf5_all_languages"), KConfig::NoGlobals, QStandardPaths::GenericDataLocation)) #endif { #ifndef NOKDE setStringList(m_systemLangList->groupList()); #else QStringList ll; QList allLocales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::AnyCountry); - foreach(const QLocale& l, allLocales) + foreach (const QLocale& l, allLocales) ll.append(l.name()); - ll=ll.toSet().toList(); + ll = ll.toSet().toList(); setStringList(ll); #endif - if (type==WithEmptyLang) insertRows(rowCount(), 1); + if (type == WithEmptyLang) insertRows(rowCount(), 1); #if 0 //KDE5PORT KIconLoader::global()->addExtraDesktopThemes(); #endif @@ -94,43 +93,38 @@ QVariant LanguageListModel::data(const QModelIndex& index, int role) const { - if (role==Qt::DecorationRole) - { + if (role == Qt::DecorationRole) { #if 0 //#ifndef NOKDE - static QMap iconCache; + static QMap iconCache; - QString langCode=stringList().at(index.row()); - if (!iconCache.contains(langCode)) - { - QString code=QLocale(langCode).name(); + QString langCode = stringList().at(index.row()); + if (!iconCache.contains(langCode)) { + QString code = QLocale(langCode).name(); QString path; - if (code.contains('_')) code=QString::fromRawData(code.unicode()+3, 2).toLower(); - if (code!="C") - { + if (code.contains('_')) code = QString::fromRawData(code.unicode() + 3, 2).toLower(); + if (code != "C") { static const QString flagPath("l10n/%1/flag.png"); - path=QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("locale/") + flagPath.arg(code)); + path = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("locale/") + flagPath.arg(code)); } - iconCache[langCode]=QIcon(path); + iconCache[langCode] = QIcon(path); } return iconCache.value(langCode); #endif - } - else if (role==Qt::DisplayRole) - { - const QString& code=stringList().at(index.row()); + } else if (role == Qt::DisplayRole) { + const QString& code = stringList().at(index.row()); if (code.isEmpty()) return code; //qCDebug(LOKALIZE_LOG)<<"languageCodeToName"< displayNames(stringList().size()); if (displayNames.at(index.row()).length()) return displayNames.at(index.row()); #ifndef NOKDE - return QVariant::fromValue( - displayNames[index.row()]=KConfigGroup(m_systemLangList,code).readEntry("Name")%QStringLiteral(" (")%code%')'); + return QVariant::fromValue( + displayNames[index.row()] = KConfigGroup(m_systemLangList, code).readEntry("Name") % QStringLiteral(" (") % code % ')'); #else QLocale l(code); // if (l.language()==QLocale::C && code!="C") return QVariant::fromValue( - displayNames[index.row()]=QLocale::languageToString(l.language())%QStringLiteral(" (")%code%')'); + displayNames[index.row()] = QLocale::languageToString(l.language()) % QStringLiteral(" (") % code % ')'); #endif } return QStringListModel::data(index, role); @@ -148,7 +142,7 @@ QString LanguageListModel::langCodeForSortModelRow(int row) { - return stringList().at(m_sortModel->mapToSource(m_sortModel->index(row,0)).row()); + return stringList().at(m_sortModel->mapToSource(m_sortModel->index(row, 0)).row()); } @@ -163,22 +157,21 @@ QString getTargetLangCode(const QString& title, bool askUser) { - if (!askUser) - { + if (!askUser) { if (Project::instance()->targetLangCode().length()) return Project::instance()->targetLangCode(); return QLocale::system().name(); } QDialog dlg(SettingsController::instance()->mainWindowPtr()); dlg.setWindowTitle(title); - QHBoxLayout* l=new QHBoxLayout(&dlg); + QHBoxLayout* l = new QHBoxLayout(&dlg); l->addWidget(new QLabel(i18n("Target language:"), &dlg)); - QComboBox* lc=new QComboBox(&dlg); + QComboBox* lc = new QComboBox(&dlg); l->addWidget(lc); lc->setModel(LanguageListModel::instance()->sortModel()); - lc->setCurrentIndex(LanguageListModel::instance()->sortModelRowForLangCode( Project::instance()->targetLangCode() )); - QDialogButtonBox* btn=new QDialogButtonBox(QDialogButtonBox::Ok, &dlg); + lc->setCurrentIndex(LanguageListModel::instance()->sortModelRowForLangCode(Project::instance()->targetLangCode())); + QDialogButtonBox* btn = new QDialogButtonBox(QDialogButtonBox::Ok, &dlg); l->addWidget(btn); QObject::connect(btn, &QDialogButtonBox::accepted, &dlg, &QDialog::accept); QObject::connect(btn, &QDialogButtonBox::rejected, &dlg, &QDialog::reject); diff --git a/src/common/stemming.h b/src/common/stemming.h --- a/src/common/stemming.h +++ b/src/common/stemming.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, diff --git a/src/common/stemming.cpp b/src/common/stemming.cpp --- a/src/common/stemming.cpp +++ b/src/common/stemming.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -33,7 +33,7 @@ QString enhanceLangCode(const QString& langCode) { - if (langCode.length()!=2) + if (langCode.length() != 2) return langCode; return QLocale(langCode).name(); @@ -44,16 +44,15 @@ #include #include -struct SpellerAndCodec -{ +struct SpellerAndCodec { Hunspell* speller; QTextCodec* codec; - SpellerAndCodec():speller(0), codec(0){} + SpellerAndCodec(): speller(0), codec(0) {} SpellerAndCodec(const QString& langCode); }; SpellerAndCodec::SpellerAndCodec(const QString& langCode) -: speller(0), codec(0) + : speller(0), codec(0) { #ifdef Q_OS_MAC QString dictPath = QStringLiteral("/Applications/LibreOffice.app/Contents/Resources/extensions/dict-") % langCode.leftRef(2) % '/'; @@ -69,34 +68,32 @@ QString dic = dictPath % langCode % QLatin1String(".dic"); if (!QFileInfo::exists(dic)) dic = dictPath % enhanceLangCode(langCode) % QLatin1String(".dic"); - if (QFileInfo::exists(dic)) - { + if (QFileInfo::exists(dic)) { speller = new Hunspell(QString(dictPath % langCode % ".aff").toLatin1().constData(), dic.toLatin1().constData()); codec = QTextCodec::codecForName(speller->get_dic_encoding()); if (!codec) codec = QTextCodec::codecForLocale(); } } -static QMap hunspellers; +static QMap hunspellers; #endif QString stem(const QString& langCode, const QString& word) { - QString result=word; + QString result = word; #ifdef HAVE_HUNSPELL static QMutex mutex; QMutexLocker locker(&mutex); - if (!hunspellers.contains(langCode)) - { - hunspellers.insert(langCode,SpellerAndCodec(langCode)); + if (!hunspellers.contains(langCode)) { + hunspellers.insert(langCode, SpellerAndCodec(langCode)); } SpellerAndCodec sc(hunspellers.value(langCode)); - Hunspell* speller=sc.speller; + Hunspell* speller = sc.speller; if (!speller) return word; @@ -106,7 +103,7 @@ int n2 = speller->stem(&result2, result1, n1); if (n2) - result=sc.codec->toUnicode(result2[0]); + result = sc.codec->toUnicode(result2[0]); speller->free_list(&result1, n1); speller->free_list(&result2, n2); @@ -118,9 +115,9 @@ void cleanupSpellers() { #ifdef HAVE_HUNSPELL - foreach(const SpellerAndCodec& sc, hunspellers) + foreach (const SpellerAndCodec& sc, hunspellers) delete sc.speller; - + #endif } diff --git a/src/common/termlabel.h b/src/common/termlabel.h --- a/src/common/termlabel.h +++ b/src/common/termlabel.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -28,23 +28,24 @@ #include "glossary.h" #include "project.h" -namespace GlossaryNS { +namespace GlossaryNS +{ /** * flowlayout item */ class TermLabel: public QLabel//QPushButton { Q_OBJECT public: - TermLabel(QAction* a=0): m_capFirst(false), m_action(a){}; - ~TermLabel(){} + TermLabel(QAction* a = 0): m_capFirst(false), m_action(a) {}; + ~TermLabel() {} /** * @param term is the term matched * @param entry is a whole entry */ void setText(const QString& term, const QByteArray& entryId, bool capFirst); - void mousePressEvent (QMouseEvent* /* event*/); + void mousePressEvent(QMouseEvent* /* event*/); public slots: void insert(); diff --git a/src/common/termlabel.cpp b/src/common/termlabel.cpp --- a/src/common/termlabel.cpp +++ b/src/common/termlabel.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -52,72 +52,67 @@ // // { // // if (event->type() != QEvent::Shortcut) // // return QLabel::event(event); -// // +// // // // // qCWarning(LOKALIZE_LOG) << "dsds " << m_termTransl; // // emit insertTerm(m_termTransl); // // return true; // // } void TermLabel::insert() { - GlossaryNS::Glossary* glossary=Project::instance()->glossary(); + GlossaryNS::Glossary* glossary = Project::instance()->glossary(); if (m_entryId.isEmpty()) return; QString termTrans; - const QStringList& termTarget=glossary->terms(m_entryId, Project::instance()->targetLangCode()); - if( termTarget.count()>1) - { + const QStringList& termTarget = glossary->terms(m_entryId, Project::instance()->targetLangCode()); + if (termTarget.count() > 1) { QMenu menu; - int limit=termTarget.count(); + int limit = termTarget.count(); menu.setActiveAction(menu.addAction(termTarget.at(0))); - int i=1; - for (;itext(); - } - else if (termTarget.count() == 1) - termTrans=termTarget.first(); + termTrans = txt->text(); + } else if (termTarget.count() == 1) + termTrans = termTarget.first(); if (m_capFirst && !termTrans.isEmpty()) - termTrans[0]=termTrans.at(0).toUpper(); + termTrans[0] = termTrans.at(0).toUpper(); emit insertTerm(termTrans); } -void TermLabel::mousePressEvent (QMouseEvent* event) +void TermLabel::mousePressEvent(QMouseEvent* event) { - if (event->button()==Qt::RightButton) - { + if (event->button() == Qt::RightButton) { QMenu menu; - menu.addAction(i18nc("@action:inmenu Edit term","Edit")); + menu.addAction(i18nc("@action:inmenu Edit term", "Edit")); - QAction* txt=menu.exec(event->globalPos()); - if (txt) - { - GlossaryNS::GlossaryWindow* glossaryWindow=Project::instance()->showGlossary(); + QAction* txt = menu.exec(event->globalPos()); + if (txt) { + GlossaryNS::GlossaryWindow* glossaryWindow = Project::instance()->showGlossary(); if (glossaryWindow) glossaryWindow->selectEntry(m_entryId); } - } - else + } else insert(); } void TermLabel::setText(const QString& term, const QByteArray& entryId, bool capFirst) { - m_entryId=entryId; - m_capFirst=capFirst; + m_entryId = entryId; + m_capFirst = capFirst; static const QString n = QStringLiteral(" \n "); - QLabel::setText(QString(term + QString(m_action?QString(QStringLiteral(" [") % m_action->shortcut().toString(QKeySequence::NativeText)%QStringLiteral("] \n ")):n)//m_shortcut - % Project::instance()->glossary()->terms(m_entryId, Project::instance()->targetLangCode()).join(n) - % n)); + QLabel::setText(QString(term + QString(m_action ? QString(QStringLiteral(" [") % m_action->shortcut().toString(QKeySequence::NativeText) % QStringLiteral("] \n ")) : n) //m_shortcut + % Project::instance()->glossary()->terms(m_entryId, Project::instance()->targetLangCode()).join(n) + % n)); } @@ -137,7 +132,7 @@ //connect(this,SIGNAL(clicked(bool)),this,SLOT(insert())); } -void QueryResultBtn::mousePressEvent (QMouseEvent*/* event*/) +void QueryResultBtn::mousePressEvent(QMouseEvent*/* event*/) { emit insertText(m_text); } diff --git a/src/common/winhelpers.cpp b/src/common/winhelpers.cpp --- a/src/common/winhelpers.cpp +++ b/src/common/winhelpers.cpp @@ -6,7 +6,7 @@ QString fullUserName() { ushort name[100]; - unsigned long size=99; + unsigned long size = 99; GetUserNameW((LPWSTR)name, &size); return QString::fromUtf16(name); } diff --git a/src/completionstorage.h b/src/completionstorage.h --- a/src/completionstorage.h +++ b/src/completionstorage.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -30,8 +30,8 @@ class CompletionStorage { private: - CompletionStorage():rxSplit("\\W+|\\d+"){}; - ~CompletionStorage(){}; + CompletionStorage(): rxSplit("\\W+|\\d+") {}; + ~CompletionStorage() {}; static CompletionStorage* _instance; static void cleanupCompletionStorage(); public: @@ -43,7 +43,7 @@ public: QRegExp rxSplit; private: - QMap m_words;//how many occurencies a word has + QMap m_words; //how many occurencies a word has //QSet save which files we scanned? }; diff --git a/src/completionstorage.cpp b/src/completionstorage.cpp --- a/src/completionstorage.cpp +++ b/src/completionstorage.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -30,17 +30,16 @@ #include -CompletionStorage* CompletionStorage::_instance=0; +CompletionStorage* CompletionStorage::_instance = 0; void CompletionStorage::cleanupCompletionStorage() { delete CompletionStorage::_instance; CompletionStorage::_instance = 0; } CompletionStorage* CompletionStorage::instance() { - if (_instance==0 ) - { - _instance=new CompletionStorage(); + if (_instance == 0) { + _instance = new CompletionStorage(); qAddPostRoutine(CompletionStorage::cleanupCompletionStorage); } return _instance; @@ -50,47 +49,43 @@ void CompletionStorage::scanCatalog(Catalog* catalog) { if (!catalog->numberOfEntries()) return; - QTime a;a.start(); + QTime a; a.start(); - int wordCompletionLength=Settings::self()->wordCompletionLength(); + int wordCompletionLength = Settings::self()->wordCompletionLength(); /* we can't skip the scanning because there might be explicit completion triggered if (wordCompletionLength<3 || !catalog->numberOfEntries()) return; */ - wordCompletionLength+=3;//only long words + wordCompletionLength += 3; //only long words - QString accel=Project::instance()->accel(); + QString accel = Project::instance()->accel(); DocPosition pos(0); - do - { - QString string=catalog->targetWithTags(pos).string; + do { + QString string = catalog->targetWithTags(pos).string; string.remove(accel); - const QStringList& words=string.toLower().split(rxSplit,QString::SkipEmptyParts); - foreach(const QString& word, words) - { - if (word.length()url()<<"for word completion in"<url() << "for word completion in" << a.elapsed() << "msecs"; } QStringList CompletionStorage::makeCompletion(const QString& word) const { //QTime a;a.start(); if (word.isEmpty()) return QStringList(); - QMultiMap hits; //we use the fact that qmap sorts it's items by keys - QString cleanWord=word.toLower(); - QMap::const_iterator it=m_words.lowerBound(cleanWord); - while(it!=m_words.constEnd() && it.key().startsWith(cleanWord)) - { - hits.insert(-it.value(),it.key().mid(word.length())); + QMultiMap hits; //we use the fact that qmap sorts it's items by keys + QString cleanWord = word.toLower(); + QMap::const_iterator it = m_words.lowerBound(cleanWord); + while (it != m_words.constEnd() && it.key().startsWith(cleanWord)) { + hits.insert(-it.value(), it.key().mid(word.length())); ++it; } //qCDebug(LOKALIZE_LOG)<<"hits generated in"< #ifndef NOKDE -namespace Sonnet{class Dialog;} -namespace Sonnet{class BackgroundChecker;} +namespace Sonnet +{ +class Dialog; +} +namespace Sonnet +{ +class BackgroundChecker; +} #include @@ -51,16 +57,18 @@ class CatalogView; class MsgCtxtView; class AltTransView; -namespace GlossaryNS{class GlossaryView;} +namespace GlossaryNS +{ +class GlossaryView; +} -struct EditorState -{ +struct EditorState { public: - EditorState(): entry(0){} - EditorState(const EditorState& s):dockWidgets(s.dockWidgets), filePath(s.filePath), entry(0) {} - ~EditorState(){} + EditorState(): entry(0) {} + EditorState(const EditorState& s): dockWidgets(s.dockWidgets), filePath(s.filePath), entry(0) {} + ~EditorState() {} QByteArray dockWidgets; QString filePath; @@ -88,45 +96,72 @@ #define qdbuscpp2xml public: - EditorTab(QWidget* parent, bool valid=true); + EditorTab(QWidget* parent, bool valid = true); ~EditorTab(); //interface for LokalizeMainWindow void hideDocks(); void showDocks(); QString currentFilePath(); void setFullPathShown(bool); - void setProperCaption(QString,bool);//reimpl to remove ' - Lokalize' + void setProperCaption(QString, bool); //reimpl to remove ' - Lokalize' public slots: void setProperFocus(); public: bool queryClose(); EditorState state(); #ifndef NOKDE - KXMLGUIClient* guiClient(){return (KXMLGUIClient*)this;} + KXMLGUIClient* guiClient() + { + return (KXMLGUIClient*)this; + } QString dbusObjectPath(); - int dbusId(){return m_dbusId;} - QObject* adaptor(){return m_adaptor;} + int dbusId() + { + return m_dbusId; + } + QObject* adaptor() + { + return m_adaptor; + } #endif //wrapper for cmdline handling void mergeOpen(QString mergeFilePath); - bool fileOpen(QString filePath=QString(), QString suggestedDirPath=QString(), bool silent=false); + bool fileOpen(QString filePath = QString(), QString suggestedDirPath = QString(), bool silent = false); public slots: //for undo/redo, views void gotoEntry(DocPosition pos); void gotoEntry(DocPosition pos, int selection); #ifdef qdbuscpp2xml - Q_SCRIPTABLE void gotoEntry(int entry){gotoEntry(DocPosition(entry));} - Q_SCRIPTABLE void gotoEntryForm(int entry,int form){gotoEntry(DocPosition(entry,form));} - Q_SCRIPTABLE void gotoEntryFormOffset(int entry,int form, int offset){gotoEntry(DocPosition(entry,form,offset));} - Q_SCRIPTABLE void gotoEntryFormOffsetSelection(int entry,int form, int offset, int selection){gotoEntry(DocPosition(entry,form,offset),selection);} + Q_SCRIPTABLE void gotoEntry(int entry) + { + gotoEntry(DocPosition(entry)); + } + Q_SCRIPTABLE void gotoEntryForm(int entry, int form) + { + gotoEntry(DocPosition(entry, form)); + } + Q_SCRIPTABLE void gotoEntryFormOffset(int entry, int form, int offset) + { + gotoEntry(DocPosition(entry, form, offset)); + } + Q_SCRIPTABLE void gotoEntryFormOffsetSelection(int entry, int form, int offset, int selection) + { + gotoEntry(DocPosition(entry, form, offset), selection); + } Q_SCRIPTABLE QString currentEntryId(); - Q_SCRIPTABLE int currentEntry(){return m_currentPos.entry;} - Q_SCRIPTABLE int currentForm(){return m_currentPos.form;} + Q_SCRIPTABLE int currentEntry() + { + return m_currentPos.entry; + } + Q_SCRIPTABLE int currentForm() + { + return m_currentPos.form; + } Q_SCRIPTABLE QString selectionInTarget(); Q_SCRIPTABLE QString selectionInSource(); @@ -145,18 +180,27 @@ Q_SCRIPTABLE void addAlternateTranslation(int entry, const QString& translation); Q_SCRIPTABLE void addTemporaryAlternateTranslation(int entry, const QString& translation); - Q_SCRIPTABLE QString currentFile(){return currentFilePath();} + Q_SCRIPTABLE QString currentFile() + { + return currentFilePath(); + } Q_SCRIPTABLE QByteArray currentFileContents(); Q_SCRIPTABLE QString sourceLangCode(); Q_SCRIPTABLE QString targetLangCode(); Q_SCRIPTABLE void attachAlternateTranslationFile(const QString& path); - Q_SCRIPTABLE void openSyncSource(QString path){mergeOpen(path);} + Q_SCRIPTABLE void openSyncSource(QString path) + { + mergeOpen(path); + } Q_SCRIPTABLE void reloadFile(); #endif - Q_SCRIPTABLE bool saveFile(const QString& filePath=QString()); - Q_SCRIPTABLE bool saveFileAs(const QString& defaultPath=QString()); - Q_SCRIPTABLE void close(){return parent()->deleteLater();} + Q_SCRIPTABLE bool saveFile(const QString& filePath = QString()); + Q_SCRIPTABLE bool saveFileAs(const QString& defaultPath = QString()); + Q_SCRIPTABLE void close() + { + return parent()->deleteLater(); + } Q_SCRIPTABLE void gotoNextUnfiltered(); Q_SCRIPTABLE void gotoPrevUnfiltered(); Q_SCRIPTABLE void gotoFirstUnfiltered(); @@ -171,14 +215,20 @@ Q_SCRIPTABLE bool findEntryBySourceContext(const QString& source, const QString& ctxt); #ifndef NOKDE - Q_SCRIPTABLE bool isValid(){return m_valid;} - Q_SCRIPTABLE void setSrcFileOpenRequestAccepted(bool a){m_srcFileOpenRequestAccepted=a;} + Q_SCRIPTABLE bool isValid() + { + return m_valid; + } + Q_SCRIPTABLE void setSrcFileOpenRequestAccepted(bool a) + { + m_srcFileOpenRequestAccepted = a; + } #endif private slots: #ifndef NOKDE - void highlightFound(const QString &,int,int);//for find/replace - void highlightFound_(const QString &,int,int);//for find/replace + void highlightFound(const QString &, int, int); //for find/replace + void highlightFound_(const QString &, int, int); //for find/replace #endif void lookupSelectionInTranslationMemory(); @@ -204,7 +254,7 @@ void replace(); void replaceNext();//internal - void doReplace(const QString&,int,int,int);//internal + void doReplace(const QString&, int, int, int); //internal void cleanupReplace();//internal #endif @@ -231,8 +281,8 @@ #ifndef NOKDE void spellcheck(); void spellcheckNext(); - void spellcheckShow(const QString&,int); - void spellcheckReplace(QString,int,const QString&); + void spellcheckShow(const QString&, int); + void spellcheckReplace(QString, int, const QString&); void spellcheckStop(); void spellcheckCancel(); #endif @@ -257,7 +307,7 @@ protected: void paintEvent(QPaintEvent* event); - + private: void setupAccel(); void setupActions(); @@ -285,16 +335,16 @@ Sonnet::BackgroundChecker* m_sonnetChecker; Sonnet::Dialog* m_sonnetDialog; int m_spellcheckStartUndoIndex; - bool m_spellcheckStop:1; + bool m_spellcheckStop: 1; #endif - bool m_currentIsApproved:1; //for statusbar animation - bool m_currentIsUntr:1; //for statusbar animation + bool m_currentIsApproved: 1; //for statusbar animation + bool m_currentIsUntr: 1; //for statusbar animation - bool m_fullPathShown:1; + bool m_fullPathShown: 1; #ifndef NOKDE - bool m_doReplaceCalled:1;//used to prevent non-clean catalog status + bool m_doReplaceCalled: 1; //used to prevent non-clean catalog status KFind* m_find; KReplace* m_replace; #endif @@ -338,7 +388,7 @@ Q_SCRIPTABLE void entryDisplayed(); void signalNewEntryDisplayed(const DocPosition&); - void signalEntryWithMergeDisplayed(bool,const DocPosition&); + void signalEntryWithMergeDisplayed(bool, const DocPosition&); void signalFirstDisplayed(bool); void signalLastDisplayed(bool); diff --git a/src/editortab.cpp b/src/editortab.cpp --- a/src/editortab.cpp +++ b/src/editortab.cpp @@ -88,28 +88,28 @@ EditorTab::EditorTab(QWidget* parent, bool valid) - : LokalizeSubwindowBase2(parent) - , m_project(Project::instance()) - , m_catalog(new Catalog(this)) - , m_view(new EditorView(this,m_catalog/*,new keyEventHandler(this,m_catalog)*/)) + : LokalizeSubwindowBase2(parent) + , m_project(Project::instance()) + , m_catalog(new Catalog(this)) + , m_view(new EditorView(this, m_catalog/*,new keyEventHandler(this,m_catalog)*/)) #ifndef NOKDE - , m_sonnetDialog(0) - , m_spellcheckStartUndoIndex(0) - , m_spellcheckStop(false) + , m_sonnetDialog(0) + , m_spellcheckStartUndoIndex(0) + , m_spellcheckStop(false) #endif - , m_currentIsApproved(true) - , m_currentIsUntr(true) - , m_fullPathShown(false) + , m_currentIsApproved(true) + , m_currentIsUntr(true) + , m_fullPathShown(false) #ifndef NOKDE - , m_doReplaceCalled(false) - , m_find(0) - , m_replace(0) + , m_doReplaceCalled(false) + , m_find(0) + , m_replace(0) #endif - , m_syncView(0) - , m_syncViewSecondary(0) + , m_syncView(0) + , m_syncViewSecondary(0) #ifndef NOKDE - , m_valid(valid) - , m_dbusId(-1) + , m_valid(valid) + , m_dbusId(-1) #endif { //QTime chrono;chrono.start(); @@ -132,7 +132,7 @@ connect(m_view, QOverload::of(&EditorView::gotoEntryRequested), this, QOverload::of(&EditorTab::gotoEntry)); connect(m_view, &EditorView::tmLookupRequested, this, &EditorTab::lookupSelectionInTranslationMemory); - connect(this, &EditorTab::fileOpened, this, &EditorTab::indexWordsForCompletion,Qt::QueuedConnection); + connect(this, &EditorTab::fileOpened, this, &EditorTab::indexWordsForCompletion, Qt::QueuedConnection); connect(m_catalog, &Catalog::signalFileAutoSaveFailed, this, &EditorTab::fileAutoSaveFailedWarning); @@ -151,8 +151,7 @@ disconnect(m_catalog, &Catalog::signalNumberOfFuzziesChanged, this, &EditorTab::numberOfFuzziesChanged); disconnect(m_catalog, &Catalog::signalNumberOfEmptyChanged, this, &EditorTab::numberOfUntranslatedChanged); - if (!m_catalog->isEmpty()) - { + if (!m_catalog->isEmpty()) { emit fileAboutToBeClosed(); emit fileClosed(); emit fileClosed(currentFile()); @@ -166,31 +165,31 @@ void EditorTab::setupStatusBar() { - statusBarItems.insert(ID_STATUS_CURRENT,i18nc("@info:status message entry","Current: %1",0)); - statusBarItems.insert(ID_STATUS_TOTAL,i18nc("@info:status message entries","Total: %1",0)); - statusBarItems.insert(ID_STATUS_FUZZY,i18nc("@info:status message entries\n'fuzzy' in gettext terminology","Not ready: %1",0)); - statusBarItems.insert(ID_STATUS_UNTRANS,i18nc("@info:status message entries","Untranslated: %1",0)); - statusBarItems.insert(ID_STATUS_ISFUZZY,QString()); + statusBarItems.insert(ID_STATUS_CURRENT, i18nc("@info:status message entry", "Current: %1", 0)); + statusBarItems.insert(ID_STATUS_TOTAL, i18nc("@info:status message entries", "Total: %1", 0)); + statusBarItems.insert(ID_STATUS_FUZZY, i18nc("@info:status message entries\n'fuzzy' in gettext terminology", "Not ready: %1", 0)); + statusBarItems.insert(ID_STATUS_UNTRANS, i18nc("@info:status message entries", "Untranslated: %1", 0)); + statusBarItems.insert(ID_STATUS_ISFUZZY, QString()); connect(m_catalog, &Catalog::signalNumberOfFuzziesChanged, this, &EditorTab::numberOfFuzziesChanged); connect(m_catalog, &Catalog::signalNumberOfEmptyChanged, this, &EditorTab::numberOfUntranslatedChanged); } #ifndef NOKDE void LokalizeSubwindowBase::reflectNonApprovedCount(int count, int total) { - QString text=i18nc("@info:status message entries\n'fuzzy' in gettext terminology","Not ready: %1", count); + QString text = i18nc("@info:status message entries\n'fuzzy' in gettext terminology", "Not ready: %1", count); if (count && total) - text+=i18nc("percentages in statusbar", " (%1%)", int(100.0*count/total)); - statusBarItems.insert(ID_STATUS_FUZZY,text); + text += i18nc("percentages in statusbar", " (%1%)", int(100.0 * count / total)); + statusBarItems.insert(ID_STATUS_FUZZY, text); } void LokalizeSubwindowBase::reflectUntranslatedCount(int count, int total) { - QString text=i18nc("@info:status message entries","Untranslated: %1", count); + QString text = i18nc("@info:status message entries", "Untranslated: %1", count); if (count && total) - text+=i18nc("percentages in statusbar", " (%1%)", int(100.0*count/total)); - statusBarItems.insert(ID_STATUS_UNTRANS,text); + text += i18nc("percentages in statusbar", " (%1%)", int(100.0 * count / total)); + statusBarItems.insert(ID_STATUS_UNTRANS, text); } #endif @@ -212,120 +211,116 @@ setXMLFile(QStringLiteral("editorui.rc")); QAction *action; - KActionCollection* ac=actionCollection(); + KActionCollection* ac = actionCollection(); KActionCategory* actionCategory; - KActionCategory* file=new KActionCategory(i18nc("@title actions category","File"), ac); - KActionCategory* nav=new KActionCategory(i18nc("@title actions category","Navigation"), ac); - KActionCategory* edit=new KActionCategory(i18nc("@title actions category","Editing"), ac); - KActionCategory* sync1=new KActionCategory(i18n("Synchronization 1"), ac); - KActionCategory* sync2=new KActionCategory(i18n("Synchronization 2"), ac); - KActionCategory* tm=new KActionCategory(i18n("Translation Memory"), ac); - KActionCategory* glossary=new KActionCategory(i18nc("@title actions category","Glossary"), actionCollection()); + KActionCategory* file = new KActionCategory(i18nc("@title actions category", "File"), ac); + KActionCategory* nav = new KActionCategory(i18nc("@title actions category", "Navigation"), ac); + KActionCategory* edit = new KActionCategory(i18nc("@title actions category", "Editing"), ac); + KActionCategory* sync1 = new KActionCategory(i18n("Synchronization 1"), ac); + KActionCategory* sync2 = new KActionCategory(i18n("Synchronization 2"), ac); + KActionCategory* tm = new KActionCategory(i18n("Translation Memory"), ac); + KActionCategory* glossary = new KActionCategory(i18nc("@title actions category", "Glossary"), actionCollection()); //KActionCategory* tools=new KActionCategory(i18nc("@title actions category","Tools"), actionCollection()); #ifndef Q_OS_DARWIN QLocale::Language systemLang = QLocale::system().language(); #endif //BEGIN dockwidgets - int i=0; + int i = 0; QVector altactions(ALTTRANS_SHORTCUTS); - Qt::Key altlist[ALTTRANS_SHORTCUTS]= - { - Qt::Key_1, - Qt::Key_2, - Qt::Key_3, - Qt::Key_4, - Qt::Key_5, - Qt::Key_6, - Qt::Key_7, - Qt::Key_8, - Qt::Key_9 - }; + Qt::Key altlist[ALTTRANS_SHORTCUTS] = { + Qt::Key_1, + Qt::Key_2, + Qt::Key_3, + Qt::Key_4, + Qt::Key_5, + Qt::Key_6, + Qt::Key_7, + Qt::Key_8, + Qt::Key_9 + }; QAction* altaction; - for (i=0;iaddAction(QStringLiteral("alttrans_insert_%1").arg(i)); - ac->setDefaultShortcut(altaction, QKeySequence(Qt::ALT+altlist[i])); - altaction->setText(i18nc("@action:inmenu","Insert alternate translation #%1",QString::number(i))); - altactions[i]=altaction; + for (i = 0; i < ALTTRANS_SHORTCUTS; ++i) { + altaction = tm->addAction(QStringLiteral("alttrans_insert_%1").arg(i)); + ac->setDefaultShortcut(altaction, QKeySequence(Qt::ALT + altlist[i])); + altaction->setText(i18nc("@action:inmenu", "Insert alternate translation #%1", QString::number(i))); + altactions[i] = altaction; } m_altTransView = new AltTransView(this, m_catalog, altactions); addDockWidget(Qt::BottomDockWidgetArea, m_altTransView); actionCollection()->addAction(QStringLiteral("showmsgiddiff_action"), m_altTransView->toggleViewAction()); - connect (this, QOverload::of(&EditorTab::signalNewEntryDisplayed), m_altTransView, QOverload::of(&AltTransView::slotNewEntryDisplayed)); - connect (m_altTransView, &AltTransView::textInsertRequested, m_view, &EditorView::insertTerm); - connect (m_altTransView, &AltTransView::refreshRequested, m_view, QOverload<>::of(&EditorView::gotoEntry), Qt::QueuedConnection); - connect (m_catalog, QOverload<>::of(&Catalog::signalFileLoaded), m_altTransView, &AltTransView::fileLoaded); + connect(this, QOverload::of(&EditorTab::signalNewEntryDisplayed), m_altTransView, QOverload::of(&AltTransView::slotNewEntryDisplayed)); + connect(m_altTransView, &AltTransView::textInsertRequested, m_view, &EditorView::insertTerm); + connect(m_altTransView, &AltTransView::refreshRequested, m_view, QOverload<>::of(&EditorView::gotoEntry), Qt::QueuedConnection); + connect(m_catalog, QOverload<>::of(&Catalog::signalFileLoaded), m_altTransView, &AltTransView::fileLoaded); m_syncView = new MergeView(this, m_catalog, true); addDockWidget(Qt::BottomDockWidgetArea, m_syncView); sync1->addAction(QStringLiteral("showmergeview_action"), m_syncView->toggleViewAction()); - connect (this, QOverload::of(&EditorTab::signalNewEntryDisplayed), m_syncView, QOverload::of(&MergeView::slotNewEntryDisplayed)); - connect (m_catalog, QOverload<>::of(&Catalog::signalFileLoaded), m_syncView, &MergeView::cleanup); - connect (m_syncView, &MergeView::gotoEntry, this, QOverload::of(&EditorTab::gotoEntry)); + connect(this, QOverload::of(&EditorTab::signalNewEntryDisplayed), m_syncView, QOverload::of(&MergeView::slotNewEntryDisplayed)); + connect(m_catalog, QOverload<>::of(&Catalog::signalFileLoaded), m_syncView, &MergeView::cleanup); + connect(m_syncView, &MergeView::gotoEntry, this, QOverload::of(&EditorTab::gotoEntry)); m_syncViewSecondary = new MergeView(this, m_catalog, false); addDockWidget(Qt::BottomDockWidgetArea, m_syncViewSecondary); sync2->addAction(QStringLiteral("showmergeviewsecondary_action"), m_syncViewSecondary->toggleViewAction()); - connect (this, QOverload::of(&EditorTab::signalNewEntryDisplayed), m_syncViewSecondary, QOverload::of(&MergeView::slotNewEntryDisplayed)); - connect (m_catalog, QOverload<>::of(&Catalog::signalFileLoaded), m_syncViewSecondary, &MergeView::cleanup); - connect (m_catalog, QOverload::of(&Catalog::signalFileLoaded), m_syncViewSecondary, QOverload::of(&MergeView::mergeOpen), Qt::QueuedConnection); - connect (m_syncViewSecondary, &MergeView::gotoEntry, this, QOverload::of(&EditorTab::gotoEntry)); + connect(this, QOverload::of(&EditorTab::signalNewEntryDisplayed), m_syncViewSecondary, QOverload::of(&MergeView::slotNewEntryDisplayed)); + connect(m_catalog, QOverload<>::of(&Catalog::signalFileLoaded), m_syncViewSecondary, &MergeView::cleanup); + connect(m_catalog, QOverload::of(&Catalog::signalFileLoaded), m_syncViewSecondary, QOverload::of(&MergeView::mergeOpen), Qt::QueuedConnection); + connect(m_syncViewSecondary, &MergeView::gotoEntry, this, QOverload::of(&EditorTab::gotoEntry)); m_transUnitsView = new CatalogView(this, m_catalog); addDockWidget(Qt::LeftDockWidgetArea, m_transUnitsView); actionCollection()->addAction(QStringLiteral("showcatalogtreeview_action"), m_transUnitsView->toggleViewAction()); - connect (this, QOverload::of(&EditorTab::signalNewEntryDisplayed), m_transUnitsView, QOverload::of(&CatalogView::slotNewEntryDisplayed)); - connect (m_transUnitsView, &CatalogView::gotoEntry, this, QOverload::of(&EditorTab::gotoEntry)); - connect (m_transUnitsView, &CatalogView::escaped, this, &EditorTab::setProperFocus); - connect (m_syncView, &MergeView::mergeCatalogPointerChanged, m_transUnitsView, &CatalogView::setMergeCatalogPointer); + connect(this, QOverload::of(&EditorTab::signalNewEntryDisplayed), m_transUnitsView, QOverload::of(&CatalogView::slotNewEntryDisplayed)); + connect(m_transUnitsView, &CatalogView::gotoEntry, this, QOverload::of(&EditorTab::gotoEntry)); + connect(m_transUnitsView, &CatalogView::escaped, this, &EditorTab::setProperFocus); + connect(m_syncView, &MergeView::mergeCatalogPointerChanged, m_transUnitsView, &CatalogView::setMergeCatalogPointer); m_notesView = new MsgCtxtView(this, m_catalog); addDockWidget(Qt::LeftDockWidgetArea, m_notesView); - actionCollection()->addAction( QStringLiteral("showmsgctxt_action"), m_notesView->toggleViewAction() ); + actionCollection()->addAction(QStringLiteral("showmsgctxt_action"), m_notesView->toggleViewAction()); connect(m_catalog, QOverload<>::of(&Catalog::signalFileLoaded), m_notesView, &MsgCtxtView::cleanup); connect(m_notesView, &MsgCtxtView::srcFileOpenRequested, this, &EditorTab::dispatchSrcFileOpenRequest); connect(m_view, &EditorView::signalChanged, m_notesView, &MsgCtxtView::removeErrorNotes); connect(m_notesView, &MsgCtxtView::escaped, this, &EditorTab::setProperFocus); - action=edit->addAction(QStringLiteral("edit_addnote"), m_notesView, SLOT(addNoteUI())); + action = edit->addAction(QStringLiteral("edit_addnote"), m_notesView, SLOT(addNoteUI())); //action->setShortcut(Qt::CTRL+glist[i]); - action->setText(i18nc("@action:inmenu","Add a note")); + action->setText(i18nc("@action:inmenu", "Add a note")); QVector tmactions(TM_SHORTCUTS); - Qt::Key tmlist[TM_SHORTCUTS]= - { - Qt::Key_1, - Qt::Key_2, - Qt::Key_3, - Qt::Key_4, - Qt::Key_5, - Qt::Key_6, - Qt::Key_7, - Qt::Key_8, - Qt::Key_9, - Qt::Key_0 - }; + Qt::Key tmlist[TM_SHORTCUTS] = { + Qt::Key_1, + Qt::Key_2, + Qt::Key_3, + Qt::Key_4, + Qt::Key_5, + Qt::Key_6, + Qt::Key_7, + Qt::Key_8, + Qt::Key_9, + Qt::Key_0 + }; QAction* tmaction; - for (i=0;isetVisible(false); - tmaction=tm->addAction(QStringLiteral("tmquery_insert_%1").arg(i)); - ac->setDefaultShortcut(tmaction, QKeySequence(Qt::CTRL+tmlist[i])); - tmaction->setText(i18nc("@action:inmenu","Insert TM suggestion #%1",QString::number(i+1))); - tmactions[i]=tmaction; + tmaction = tm->addAction(QStringLiteral("tmquery_insert_%1").arg(i)); + ac->setDefaultShortcut(tmaction, QKeySequence(Qt::CTRL + tmlist[i])); + tmaction->setText(i18nc("@action:inmenu", "Insert TM suggestion #%1", QString::number(i + 1))); + tmactions[i] = tmaction; } #ifndef Q_OS_DARWIN - if (systemLang==QLocale::Czech) ac->setDefaultShortcuts(tmactions[0], QList()<setDefaultShortcuts(tmactions[0], QList() << QKeySequence(Qt::CTRL + tmlist[0]) << QKeySequence(Qt::CTRL + Qt::Key_Plus)); #endif - TM::TMView* _tmView = new TM::TMView(this,m_catalog,tmactions); + TM::TMView* _tmView = new TM::TMView(this, m_catalog, tmactions); addDockWidget(Qt::BottomDockWidgetArea, _tmView); - tm->addAction( QStringLiteral("showtmqueryview_action"), _tmView->toggleViewAction() ); + tm->addAction(QStringLiteral("showtmqueryview_action"), _tmView->toggleViewAction()); connect(_tmView, &TM::TMView::refreshRequested, m_view, QOverload<>::of(&EditorView::gotoEntry), Qt::QueuedConnection); connect(_tmView, &TM::TMView::refreshRequested, this, &EditorTab::msgStrChanged, Qt::QueuedConnection); connect(_tmView, &TM::TMView::textInsertRequested, m_view, &EditorView::insertTerm); @@ -335,106 +330,102 @@ connect(this, &EditorTab::signalNewEntryDisplayed, _tmView, QOverload::of(&TM::TMView::slotNewEntryDisplayed)); //do this after flushUpdateDBBuffer QVector gactions(GLOSSARY_SHORTCUTS); - Qt::Key glist[GLOSSARY_SHORTCUTS]= - { - Qt::Key_E, - Qt::Key_H, + Qt::Key glist[GLOSSARY_SHORTCUTS] = { + Qt::Key_E, + Qt::Key_H, // Qt::Key_G, // Qt::Key_I, // Qt::Key_J, // Qt::Key_K, - Qt::Key_K, - Qt::Key_P, - Qt::Key_N, + Qt::Key_K, + Qt::Key_P, + Qt::Key_N, // Qt::Key_Q, // Qt::Key_R, // Qt::Key_U, // Qt::Key_V, // Qt::Key_W, // Qt::Key_X, - Qt::Key_Y, + Qt::Key_Y, // Qt::Key_Z, - Qt::Key_BraceLeft, - Qt::Key_BraceRight, - Qt::Key_Semicolon, - Qt::Key_Apostrophe - }; + Qt::Key_BraceLeft, + Qt::Key_BraceRight, + Qt::Key_Semicolon, + Qt::Key_Apostrophe + }; QAction* gaction; // int i=0; - for (i=0;isetVisible(false); - gaction=glossary->addAction(QStringLiteral("glossary_insert_%1").arg(i)); - ac->setDefaultShortcut(gaction, QKeySequence(Qt::CTRL+glist[i])); - gaction->setText(i18nc("@action:inmenu","Insert term translation #%1",QString::number(i))); - gactions[i]=gaction; + gaction = glossary->addAction(QStringLiteral("glossary_insert_%1").arg(i)); + ac->setDefaultShortcut(gaction, QKeySequence(Qt::CTRL + glist[i])); + gaction->setText(i18nc("@action:inmenu", "Insert term translation #%1", QString::number(i))); + gactions[i] = gaction; } - GlossaryNS::GlossaryView* _glossaryView = new GlossaryNS::GlossaryView(this,m_catalog,gactions); + GlossaryNS::GlossaryView* _glossaryView = new GlossaryNS::GlossaryView(this, m_catalog, gactions); addDockWidget(Qt::BottomDockWidgetArea, _glossaryView); - glossary->addAction( QStringLiteral("showglossaryview_action"), _glossaryView->toggleViewAction() ); - connect (this, &EditorTab::signalNewEntryDisplayed, _glossaryView, QOverload::of(&GlossaryNS::GlossaryView::slotNewEntryDisplayed)); - connect (_glossaryView, &GlossaryNS::GlossaryView::termInsertRequested, m_view, &EditorView::insertTerm); + glossary->addAction(QStringLiteral("showglossaryview_action"), _glossaryView->toggleViewAction()); + connect(this, &EditorTab::signalNewEntryDisplayed, _glossaryView, QOverload::of(&GlossaryNS::GlossaryView::slotNewEntryDisplayed)); + connect(_glossaryView, &GlossaryNS::GlossaryView::termInsertRequested, m_view, &EditorView::insertTerm); - gaction = glossary->addAction(QStringLiteral("glossary_define"),this,SLOT(defineNewTerm())); - gaction->setText(i18nc("@action:inmenu","Define new term")); + gaction = glossary->addAction(QStringLiteral("glossary_define"), this, SLOT(defineNewTerm())); + gaction->setText(i18nc("@action:inmenu", "Define new term")); _glossaryView->addAction(gaction); - _glossaryView->setContextMenuPolicy( Qt::ActionsContextMenu); + _glossaryView->setContextMenuPolicy(Qt::ActionsContextMenu); - BinUnitsView* binUnitsView=new BinUnitsView(m_catalog,this); + BinUnitsView* binUnitsView = new BinUnitsView(m_catalog, this); addDockWidget(Qt::BottomDockWidgetArea, binUnitsView); - edit->addAction( QStringLiteral("showbinunitsview_action"), binUnitsView->toggleViewAction() ); + edit->addAction(QStringLiteral("showbinunitsview_action"), binUnitsView->toggleViewAction()); connect(m_view, &EditorView::binaryUnitSelectRequested, binUnitsView, &BinUnitsView::selectUnit); //#ifdef WEBQUERY_ENABLE #if 0 QVector wqactions(WEBQUERY_SHORTCUTS); - Qt::Key wqlist[WEBQUERY_SHORTCUTS]= - { - Qt::Key_1, - Qt::Key_2, - Qt::Key_3, - Qt::Key_4, - Qt::Key_5, - Qt::Key_6, - Qt::Key_7, - Qt::Key_8, - Qt::Key_9, - Qt::Key_0, - }; + Qt::Key wqlist[WEBQUERY_SHORTCUTS] = { + Qt::Key_1, + Qt::Key_2, + Qt::Key_3, + Qt::Key_4, + Qt::Key_5, + Qt::Key_6, + Qt::Key_7, + Qt::Key_8, + Qt::Key_9, + Qt::Key_0, + }; QAction* wqaction; - for (i=0;isetVisible(false); - wqaction=actionCollection()->addAction(QString("webquery_insert_%1").arg(i)); - wqaction->setShortcut(Qt::CTRL+Qt::ALT+wqlist[i]); + wqaction = actionCollection()->addAction(QString("webquery_insert_%1").arg(i)); + wqaction->setShortcut(Qt::CTRL + Qt::ALT + wqlist[i]); //wqaction->setShortcut(Qt::META+wqlist[i]); - wqaction->setText(i18nc("@action:inmenu","Insert WebQuery result #%1",i)); - wqactions[i]=wqaction; + wqaction->setText(i18nc("@action:inmenu", "Insert WebQuery result #%1", i)); + wqactions[i] = wqaction; } - WebQueryView* _webQueryView = new WebQueryView(this,m_catalog,wqactions); + WebQueryView* _webQueryView = new WebQueryView(this, m_catalog, wqactions); addDockWidget(Qt::BottomDockWidgetArea, _webQueryView); - actionCollection()->addAction( QStringLiteral("showwebqueryview_action"), _webQueryView->toggleViewAction() ); - connect (this, &EditorTab::signalNewEntryDisplayed, _webQueryView, SLOT(slotNewEntryDisplayed(DocPosition))); - connect (_webQueryView, SIGNAL(textInsertRequested(QString)),m_view,SLOT(insertTerm(QString))); + actionCollection()->addAction(QStringLiteral("showwebqueryview_action"), _webQueryView->toggleViewAction()); + connect(this, &EditorTab::signalNewEntryDisplayed, _webQueryView, SLOT(slotNewEntryDisplayed(DocPosition))); + connect(_webQueryView, SIGNAL(textInsertRequested(QString)), m_view, SLOT(insertTerm(QString))); #endif //END dockwidgets - actionCategory=file; + actionCategory = file; // File - action=file->addAction(KStandardAction::Save,this, SLOT(saveFile())); + action = file->addAction(KStandardAction::Save, this, SLOT(saveFile())); // action->setEnabled(false); // connect (m_catalog,SIGNAL(cleanChanged(bool)),action,SLOT(setDisabled(bool))); - connect (m_catalog, &Catalog::cleanChanged, this, &EditorTab::setModificationSign); - file->addAction(KStandardAction::SaveAs,this, SLOT(saveFileAs())); + connect(m_catalog, &Catalog::cleanChanged, this, &EditorTab::setModificationSign); + file->addAction(KStandardAction::SaveAs, this, SLOT(saveFileAs())); //action = KStandardAction::quit(qApp, SLOT(quit()), ac); //action->setText(i18nc("@action:inmenu","Close all Lokalize windows")); @@ -452,38 +443,38 @@ ac->setDefaultShortcut(action, QKeySequence( _shortcut )); action = actionCategory->addAction(QStringLiteral("file_phases")); - action->setText(i18nc("@action:inmenu","Phases...")); + action->setText(i18nc("@action:inmenu", "Phases...")); connect(action, &QAction::triggered, this, &EditorTab::openPhasesWindow); - ADD_ACTION_SHORTCUT("file_wordcount",i18nc("@action:inmenu","Word count"),Qt::CTRL+Qt::ALT+Qt::Key_C) + ADD_ACTION_SHORTCUT("file_wordcount", i18nc("@action:inmenu", "Word count"), Qt::CTRL + Qt::ALT + Qt::Key_C) connect(action, &QAction::triggered, this, &EditorTab::displayWordCount); - ADD_ACTION_SHORTCUT("file_cleartarget",i18nc("@action:inmenu","Clear all translated entries"),Qt::CTRL+Qt::ALT+Qt::Key_D) + ADD_ACTION_SHORTCUT("file_cleartarget", i18nc("@action:inmenu", "Clear all translated entries"), Qt::CTRL + Qt::ALT + Qt::Key_D) connect(action, &QAction::triggered, this, &EditorTab::clearTranslatedEntries); - ADD_ACTION_SHORTCUT("file_xliff2odf",i18nc("@action:inmenu","Merge translation into OpenDocument"),Qt::CTRL+Qt::Key_Backslash) + ADD_ACTION_SHORTCUT("file_xliff2odf", i18nc("@action:inmenu", "Merge translation into OpenDocument"), Qt::CTRL + Qt::Key_Backslash) connect(action, &QAction::triggered, this, &EditorTab::mergeIntoOpenDocument); connect(this, &EditorTab::xliffFileOpened, action, &QAction::setVisible); action->setVisible(false); //Edit - actionCategory=edit; - action=edit->addAction(KStandardAction::Undo, this, SLOT(undo())); + actionCategory = edit; + action = edit->addAction(KStandardAction::Undo, this, SLOT(undo())); connect((const TranslationUnitTextEdit*)m_view->viewPort(), &TranslationUnitTextEdit::undoRequested, this, &EditorTab::undo); connect(m_catalog, &Catalog::canUndoChanged, action, &QAction::setEnabled); action->setEnabled(false); - action=edit->addAction(KStandardAction::Redo, this, SLOT(redo())); + action = edit->addAction(KStandardAction::Redo, this, SLOT(redo())); connect((const TranslationUnitTextEdit*)m_view->viewPort(), &TranslationUnitTextEdit::redoRequested, this, &EditorTab::redo); connect(m_catalog, &Catalog::canRedoChanged, action, &QAction::setEnabled); action->setEnabled(false); - action=nav->addAction(KStandardAction::Find, this, SLOT(find())); - action=nav->addAction(KStandardAction::FindNext, this, SLOT(findNext())); - action=nav->addAction(KStandardAction::FindPrev, this, SLOT(findPrev())); - action->setText(i18nc("@action:inmenu","Change searching direction")); - action=edit->addAction(KStandardAction::Replace, this, SLOT(replace())); + action = nav->addAction(KStandardAction::Find, this, SLOT(find())); + action = nav->addAction(KStandardAction::FindNext, this, SLOT(findNext())); + action = nav->addAction(KStandardAction::FindPrev, this, SLOT(findPrev())); + action->setText(i18nc("@action:inmenu", "Change searching direction")); + action = edit->addAction(KStandardAction::Replace, this, SLOT(replace())); connect(m_view, &EditorView::findRequested, this, &EditorTab::find); connect(m_view, &EditorView::findNextRequested, this, QOverload<>::of(&EditorTab::findNext)); @@ -493,269 +484,269 @@ action = actionCategory->addAction(QStringLiteral("edit_approve"), new KToolBarPopupAction(QIcon::fromTheme(QStringLiteral("approved")), - i18nc("@option:check whether message is marked as translated/reviewed/approved (depending on your role)","Approved"), this)); - ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL+Qt::Key_U)); + i18nc("@option:check whether message is marked as translated/reviewed/approved (depending on your role)", "Approved"), this)); + ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_U)); action->setCheckable(true); connect(action, &QAction::triggered, m_view, &EditorView::toggleApprovement); connect(m_view, &EditorView::signalApprovedEntryDisplayed, this, &EditorTab::signalApprovedEntryDisplayed); connect(this, &EditorTab::signalApprovedEntryDisplayed, action, &QAction::setChecked); connect(this, &EditorTab::signalApprovedEntryDisplayed, this, &EditorTab::msgStrChanged, Qt::QueuedConnection); - m_approveAction=action; + m_approveAction = action; #ifdef NOKDE - QMenu* am=new QMenu(i18nc("@option:check whether message is marked as translated/reviewed/approved (depending on your role)","State"),this); - action=am->menuAction(); - ac->addAction(QStringLiteral("edit_state"),action); + QMenu* am = new QMenu(i18nc("@option:check whether message is marked as translated/reviewed/approved (depending on your role)", "State"), this); + action = am->menuAction(); + ac->addAction(QStringLiteral("edit_state"), action); #endif - m_stateAction=action; + m_stateAction = action; connect(Project::local(), &ProjectLocal::configChanged, this, &EditorTab::setApproveActionTitle); connect(m_catalog, &Catalog::activePhaseChanged, this, &EditorTab::setApproveActionTitle); connect(m_stateAction->menu(), &QMenu::aboutToShow, this, &EditorTab::showStatesMenu); connect(m_stateAction->menu(), &QMenu::triggered, this, &EditorTab::setState); action = actionCategory->addAction(QStringLiteral("edit_approve_go_fuzzyUntr")); - action->setText(i18nc("@action:inmenu","Approve and go to next")); + action->setText(i18nc("@action:inmenu", "Approve and go to next")); connect(action, &QAction::triggered, this, &EditorTab::toggleApprovementGotoNextFuzzyUntr); m_approveAndGoAction = action; setApproveActionTitle(); - action = actionCategory->addAction(QStringLiteral("edit_nonequiv"),m_view,SLOT(setEquivTrans(bool))); - action->setText(i18nc("@action:inmenu","Equivalent translation")); + action = actionCategory->addAction(QStringLiteral("edit_nonequiv"), m_view, SLOT(setEquivTrans(bool))); + action->setText(i18nc("@action:inmenu", "Equivalent translation")); action->setCheckable(true); connect(this, &EditorTab::signalEquivTranslatedEntryDisplayed, action, &QAction::setChecked); #ifndef Q_OS_DARWIN - int copyShortcut=Qt::CTRL+Qt::Key_Space; - if (Q_UNLIKELY( systemLang==QLocale::Korean - || systemLang==QLocale::Japanese - || systemLang==QLocale::Chinese - )) - copyShortcut=Qt::ALT+Qt::Key_Space; + int copyShortcut = Qt::CTRL + Qt::Key_Space; + if (Q_UNLIKELY(systemLang == QLocale::Korean + || systemLang == QLocale::Japanese + || systemLang == QLocale::Chinese + )) + copyShortcut = Qt::ALT + Qt::Key_Space; #else - int copyShortcut=Qt::META+Qt::Key_Space; + int copyShortcut = Qt::META + Qt::Key_Space; #endif - ADD_ACTION_SHORTCUT_ICON("edit_msgid2msgstr",i18nc("@action:inmenu","Copy source to target"),copyShortcut,"msgid2msgstr") + ADD_ACTION_SHORTCUT_ICON("edit_msgid2msgstr", i18nc("@action:inmenu", "Copy source to target"), copyShortcut, "msgid2msgstr") connect(action, &QAction::triggered, (const TranslationUnitTextEdit*)m_view->viewPort(), &TranslationUnitTextEdit::source2target); - ADD_ACTION_SHORTCUT("edit_unwrap-target",i18nc("@action:inmenu","Unwrap target"),Qt::CTRL+Qt::Key_I) + ADD_ACTION_SHORTCUT("edit_unwrap-target", i18nc("@action:inmenu", "Unwrap target"), Qt::CTRL + Qt::Key_I) connect(action, &QAction::triggered, m_view, QOverload<>::of(&EditorView::unwrap)); - action=edit->addAction(QStringLiteral("edit_clear-target"), m_view->viewPort(), SLOT(removeTargetSubstring())); - ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL+Qt::Key_D)); + action = edit->addAction(QStringLiteral("edit_clear-target"), m_view->viewPort(), SLOT(removeTargetSubstring())); + ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_D)); action->setText(i18nc("@action:inmenu", "Clear")); - action=edit->addAction(QStringLiteral("edit_tagmenu"), m_view->viewPort(), SLOT(tagMenu())); - ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL+Qt::Key_T)); + action = edit->addAction(QStringLiteral("edit_tagmenu"), m_view->viewPort(), SLOT(tagMenu())); + ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_T)); action->setText(i18nc("@action:inmenu", "Insert Tag")); - action=edit->addAction(QStringLiteral("edit_tagimmediate"), m_view->viewPort(), SLOT(tagImmediate())); - ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL+Qt::Key_M)); + action = edit->addAction(QStringLiteral("edit_tagimmediate"), m_view->viewPort(), SLOT(tagImmediate())); + ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_M)); action->setText(i18nc("@action:inmenu", "Insert Next Tag")); #ifndef NOKDE - action=edit->addAction(QStringLiteral("edit_completion"), m_view, SIGNAL(doExplicitCompletion())); - ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL+Qt::ALT+Qt::Key_Space)); + action = edit->addAction(QStringLiteral("edit_completion"), m_view, SIGNAL(doExplicitCompletion())); + ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_Space)); action->setText(i18nc("@action:inmenu", "Completion")); - action=edit->addAction(QStringLiteral("edit_spellreplace"), m_view->viewPort(), SLOT(spellReplace())); - ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL+Qt::Key_Equal)); + action = edit->addAction(QStringLiteral("edit_spellreplace"), m_view->viewPort(), SLOT(spellReplace())); + ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_Equal)); action->setText(i18nc("@action:inmenu", "Replace with best spellcheck suggestion")); #endif // action = ac->addAction("glossary_define",m_view,SLOT(defineNewTerm())); // action->setText(i18nc("@action:inmenu","Define new term")); // Go - actionCategory=nav; - action=nav->addAction(KStandardAction::Next,this, SLOT(gotoNext())); - action->setText(i18nc("@action:inmenu entry","&Next")); + actionCategory = nav; + action = nav->addAction(KStandardAction::Next, this, SLOT(gotoNext())); + action->setText(i18nc("@action:inmenu entry", "&Next")); connect(this, &EditorTab::signalLastDisplayed, action, &QAction::setDisabled); connect((const TranslationUnitTextEdit*)m_view->viewPort(), &TranslationUnitTextEdit::gotoNextRequested, this, &EditorTab::gotoNext); - action=nav->addAction(KStandardAction::Prior,this, SLOT(gotoPrev())); - action->setText(i18nc("@action:inmenu entry","&Previous")); + action = nav->addAction(KStandardAction::Prior, this, SLOT(gotoPrev())); + action->setText(i18nc("@action:inmenu entry", "&Previous")); connect(this, &EditorTab::signalFirstDisplayed, action, &QAction::setDisabled); connect((const TranslationUnitTextEdit*)m_view->viewPort(), &TranslationUnitTextEdit::gotoPrevRequested, this, &EditorTab::gotoPrev); - action=nav->addAction(KStandardAction::FirstPage,this, SLOT(gotoFirst())); + action = nav->addAction(KStandardAction::FirstPage, this, SLOT(gotoFirst())); connect((const TranslationUnitTextEdit*)m_view->viewPort(), &TranslationUnitTextEdit::gotoFirstRequested, this, &EditorTab::gotoFirst); - action->setText(i18nc("@action:inmenu","&First Entry")); - action->setShortcut(QKeySequence(Qt::CTRL+Qt::ALT+Qt::Key_Home)); + action->setText(i18nc("@action:inmenu", "&First Entry")); + action->setShortcut(QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_Home)); connect(this, &EditorTab::signalFirstDisplayed, action, &QAction::setDisabled); - action=nav->addAction(KStandardAction::LastPage,this, SLOT(gotoLast())); + action = nav->addAction(KStandardAction::LastPage, this, SLOT(gotoLast())); connect((const TranslationUnitTextEdit*)m_view->viewPort(), &TranslationUnitTextEdit::gotoLastRequested, this, &EditorTab::gotoLast); - action->setText(i18nc("@action:inmenu","&Last Entry")); - action->setShortcut(QKeySequence(Qt::CTRL+Qt::ALT+Qt::Key_End)); - connect(this, &EditorTab::signalLastDisplayed,action,&QAction::setDisabled); + action->setText(i18nc("@action:inmenu", "&Last Entry")); + action->setShortcut(QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_End)); + connect(this, &EditorTab::signalLastDisplayed, action, &QAction::setDisabled); - action=nav->addAction(KStandardAction::GotoPage, this, SLOT(gotoEntry())); - ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL+Qt::Key_G)); - action->setText(i18nc("@action:inmenu","Entry by number")); + action = nav->addAction(KStandardAction::GotoPage, this, SLOT(gotoEntry())); + ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_G)); + action->setText(i18nc("@action:inmenu", "Entry by number")); - ADD_ACTION_SHORTCUT_ICON("go_prev_fuzzy",i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology","Previous non-empty but not ready"),Qt::CTRL+Qt::Key_PageUp,"prevfuzzy") + ADD_ACTION_SHORTCUT_ICON("go_prev_fuzzy", i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology", "Previous non-empty but not ready"), Qt::CTRL + Qt::Key_PageUp, "prevfuzzy") connect(action, &QAction::triggered, this, &EditorTab::gotoPrevFuzzy); connect((const TranslationUnitTextEdit*)m_view->viewPort(), &TranslationUnitTextEdit::gotoPrevFuzzyRequested, this, &EditorTab::gotoPrevFuzzy); - connect(this, &EditorTab::signalPriorFuzzyAvailable,action,&QAction::setEnabled); + connect(this, &EditorTab::signalPriorFuzzyAvailable, action, &QAction::setEnabled); - ADD_ACTION_SHORTCUT_ICON("go_next_fuzzy",i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology","Next non-empty but not ready"),Qt::CTRL+Qt::Key_PageDown,"nextfuzzy") + ADD_ACTION_SHORTCUT_ICON("go_next_fuzzy", i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology", "Next non-empty but not ready"), Qt::CTRL + Qt::Key_PageDown, "nextfuzzy") connect(action, &QAction::triggered, this, &EditorTab::gotoNextFuzzy); connect((const TranslationUnitTextEdit*)m_view->viewPort(), &TranslationUnitTextEdit::gotoNextFuzzyRequested, this, &EditorTab::gotoNextFuzzy); - connect(this, &EditorTab::signalNextFuzzyAvailable,action,&QAction::setEnabled); + connect(this, &EditorTab::signalNextFuzzyAvailable, action, &QAction::setEnabled); - ADD_ACTION_SHORTCUT_ICON("go_prev_untrans",i18nc("@action:inmenu","Previous untranslated"),Qt::ALT+Qt::Key_PageUp,"prevuntranslated") + ADD_ACTION_SHORTCUT_ICON("go_prev_untrans", i18nc("@action:inmenu", "Previous untranslated"), Qt::ALT + Qt::Key_PageUp, "prevuntranslated") connect(action, &QAction::triggered, this, &EditorTab::gotoPrevUntranslated); connect((const TranslationUnitTextEdit*)m_view->viewPort(), &TranslationUnitTextEdit::gotoPrevUntranslatedRequested, this, &EditorTab::gotoPrevUntranslated); - connect(this, &EditorTab::signalPriorUntranslatedAvailable,action,&QAction::setEnabled); + connect(this, &EditorTab::signalPriorUntranslatedAvailable, action, &QAction::setEnabled); - ADD_ACTION_SHORTCUT_ICON("go_next_untrans",i18nc("@action:inmenu","Next untranslated"),Qt::ALT+Qt::Key_PageDown,"nextuntranslated") + ADD_ACTION_SHORTCUT_ICON("go_next_untrans", i18nc("@action:inmenu", "Next untranslated"), Qt::ALT + Qt::Key_PageDown, "nextuntranslated") connect(action, &QAction::triggered, this, &EditorTab::gotoNextUntranslated); connect((const TranslationUnitTextEdit*)m_view->viewPort(), &TranslationUnitTextEdit::gotoNextUntranslatedRequested, this, &EditorTab::gotoNextUntranslated); - connect(this, &EditorTab::signalNextUntranslatedAvailable,action,&QAction::setEnabled); + connect(this, &EditorTab::signalNextUntranslatedAvailable, action, &QAction::setEnabled); - ADD_ACTION_SHORTCUT_ICON("go_prev_fuzzyUntr",i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology","Previous not ready"),Qt::CTRL+Qt::SHIFT/*ALT*/+Qt::Key_PageUp,"prevfuzzyuntrans") + ADD_ACTION_SHORTCUT_ICON("go_prev_fuzzyUntr", i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology", "Previous not ready"), Qt::CTRL + Qt::SHIFT/*ALT*/ + Qt::Key_PageUp, "prevfuzzyuntrans") connect(action, &QAction::triggered, this, &EditorTab::gotoPrevFuzzyUntr); connect((const TranslationUnitTextEdit*)m_view->viewPort(), &TranslationUnitTextEdit::gotoPrevFuzzyUntrRequested, this, &EditorTab::gotoPrevFuzzyUntr); - connect(this, &EditorTab::signalPriorFuzzyOrUntrAvailable,action,&QAction::setEnabled); + connect(this, &EditorTab::signalPriorFuzzyOrUntrAvailable, action, &QAction::setEnabled); - ADD_ACTION_SHORTCUT_ICON("go_next_fuzzyUntr",i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology","Next not ready"),Qt::CTRL+Qt::SHIFT+Qt::Key_PageDown,"nextfuzzyuntrans") + ADD_ACTION_SHORTCUT_ICON("go_next_fuzzyUntr", i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology", "Next not ready"), Qt::CTRL + Qt::SHIFT + Qt::Key_PageDown, "nextfuzzyuntrans") connect(action, &QAction::triggered, this, QOverload<>::of(&EditorTab::gotoNextFuzzyUntr)); connect((const TranslationUnitTextEdit*)m_view->viewPort(), &TranslationUnitTextEdit::gotoNextFuzzyUntrRequested, this, QOverload<>::of(&EditorTab::gotoNextFuzzyUntr)); - connect(this, &EditorTab::signalNextFuzzyOrUntrAvailable,action,&QAction::setEnabled); + connect(this, &EditorTab::signalNextFuzzyOrUntrAvailable, action, &QAction::setEnabled); - action=nav->addAction(QStringLiteral("go_focus_earch_line"),m_transUnitsView, SLOT(setFocus())); - ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL+Qt::Key_L)); - action->setText(i18nc("@action:inmenu","Focus the search line of Translation Units view")); + action = nav->addAction(QStringLiteral("go_focus_earch_line"), m_transUnitsView, SLOT(setFocus())); + ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_L)); + action->setText(i18nc("@action:inmenu", "Focus the search line of Translation Units view")); //Bookmarks - action=nav->addAction(KStandardAction::AddBookmark,m_view,SLOT(toggleBookmark(bool))); + action = nav->addAction(KStandardAction::AddBookmark, m_view, SLOT(toggleBookmark(bool))); //action = ac->addAction("bookmark_do"); - action->setText(i18nc("@option:check","Bookmark message")); + action->setText(i18nc("@option:check", "Bookmark message")); action->setCheckable(true); //connect(action, SIGNAL(triggered(bool)),m_view,SLOT(toggleBookmark(bool))); - connect(this, &EditorTab::signalBookmarkDisplayed,action,&QAction::setChecked); + connect(this, &EditorTab::signalBookmarkDisplayed, action, &QAction::setChecked); - action=nav->addAction(QStringLiteral("bookmark_prior"),this,SLOT(gotoPrevBookmark())); - action->setText(i18nc("@action:inmenu","Previous bookmark")); - connect(this, &EditorTab::signalPriorBookmarkAvailable,action,&QAction::setEnabled); + action = nav->addAction(QStringLiteral("bookmark_prior"), this, SLOT(gotoPrevBookmark())); + action->setText(i18nc("@action:inmenu", "Previous bookmark")); + connect(this, &EditorTab::signalPriorBookmarkAvailable, action, &QAction::setEnabled); - action=nav->addAction(QStringLiteral("bookmark_next"),this,SLOT(gotoNextBookmark())); - action->setText(i18nc("@action:inmenu","Next bookmark")); - connect(this, &EditorTab::signalNextBookmarkAvailable,action,&QAction::setEnabled); + action = nav->addAction(QStringLiteral("bookmark_next"), this, SLOT(gotoNextBookmark())); + action->setText(i18nc("@action:inmenu", "Next bookmark")); + connect(this, &EditorTab::signalNextBookmarkAvailable, action, &QAction::setEnabled); //Tools - edit->addAction(KStandardAction::Spelling,this,SLOT(spellcheck())); + edit->addAction(KStandardAction::Spelling, this, SLOT(spellcheck())); - actionCategory=tm; + actionCategory = tm; // xgettext: no-c-format - ADD_ACTION_SHORTCUT("tools_tm_batch",i18nc("@action:inmenu","Fill in all exact suggestions"),Qt::CTRL+Qt::ALT+Qt::Key_B) + ADD_ACTION_SHORTCUT("tools_tm_batch", i18nc("@action:inmenu", "Fill in all exact suggestions"), Qt::CTRL + Qt::ALT + Qt::Key_B) connect(action, &QAction::triggered, _tmView, &TM::TMView::slotBatchTranslate); // xgettext: no-c-format - ADD_ACTION_SHORTCUT("tools_tm_batch_fuzzy",i18nc("@action:inmenu","Fill in all exact suggestions and mark as fuzzy"),Qt::CTRL+Qt::ALT+Qt::Key_N) + ADD_ACTION_SHORTCUT("tools_tm_batch_fuzzy", i18nc("@action:inmenu", "Fill in all exact suggestions and mark as fuzzy"), Qt::CTRL + Qt::ALT + Qt::Key_N) connect(action, &QAction::triggered, _tmView, &TM::TMView::slotBatchTranslateFuzzy); //MergeMode - action = sync1->addAction(QStringLiteral("merge_open"),m_syncView,SLOT(mergeOpen())); - action->setText(i18nc("@action:inmenu","Open file for sync/merge")); - action->setStatusTip(i18nc("@info:status","Open catalog to be merged into the current one / replicate base file changes to")); + action = sync1->addAction(QStringLiteral("merge_open"), m_syncView, SLOT(mergeOpen())); + action->setText(i18nc("@action:inmenu", "Open file for sync/merge")); + action->setStatusTip(i18nc("@info:status", "Open catalog to be merged into the current one / replicate base file changes to")); action->setToolTip(action->statusTip()); action->setWhatsThis(action->statusTip()); m_syncView->addAction(action); - action = sync1->addAction(QStringLiteral("merge_prev"),m_syncView,SLOT(gotoPrevChanged())); - action->setText(i18nc("@action:inmenu","Previous different")); - action->setStatusTip(i18nc("@info:status","Previous entry which is translated differently in the file being merged, including empty translations in merge source")); + action = sync1->addAction(QStringLiteral("merge_prev"), m_syncView, SLOT(gotoPrevChanged())); + action->setText(i18nc("@action:inmenu", "Previous different")); + action->setStatusTip(i18nc("@info:status", "Previous entry which is translated differently in the file being merged, including empty translations in merge source")); action->setToolTip(action->statusTip()); action->setWhatsThis(action->statusTip()); - ac->setDefaultShortcut(action, QKeySequence(Qt::ALT+Qt::Key_Up)); + ac->setDefaultShortcut(action, QKeySequence(Qt::ALT + Qt::Key_Up)); - connect( m_syncView, &MergeView::signalPriorChangedAvailable,action,&QAction::setEnabled); + connect(m_syncView, &MergeView::signalPriorChangedAvailable, action, &QAction::setEnabled); m_syncView->addAction(action); - action = sync1->addAction(QStringLiteral("merge_next"),m_syncView,SLOT(gotoNextChanged())); - action->setText(i18nc("@action:inmenu","Next different")); - action->setStatusTip(i18nc("@info:status","Next entry which is translated differently in the file being merged, including empty translations in merge source")); + action = sync1->addAction(QStringLiteral("merge_next"), m_syncView, SLOT(gotoNextChanged())); + action->setText(i18nc("@action:inmenu", "Next different")); + action->setStatusTip(i18nc("@info:status", "Next entry which is translated differently in the file being merged, including empty translations in merge source")); action->setToolTip(action->statusTip()); action->setWhatsThis(action->statusTip()); - ac->setDefaultShortcut(action, QKeySequence(Qt::ALT+Qt::Key_Down)); - connect( m_syncView, &MergeView::signalNextChangedAvailable,action,&QAction::setEnabled); + ac->setDefaultShortcut(action, QKeySequence(Qt::ALT + Qt::Key_Down)); + connect(m_syncView, &MergeView::signalNextChangedAvailable, action, &QAction::setEnabled); m_syncView->addAction(action); - action = sync1->addAction(QStringLiteral("merge_nextapproved"),m_syncView,SLOT(gotoNextChangedApproved())); - action->setText(i18nc("@action:inmenu","Next different approved")); - ac->setDefaultShortcut(action, QKeySequence(Qt::ALT+Qt::META+Qt::Key_Down)); - connect( m_syncView, &MergeView::signalNextChangedAvailable,action,&QAction::setEnabled); + action = sync1->addAction(QStringLiteral("merge_nextapproved"), m_syncView, SLOT(gotoNextChangedApproved())); + action->setText(i18nc("@action:inmenu", "Next different approved")); + ac->setDefaultShortcut(action, QKeySequence(Qt::ALT + Qt::META + Qt::Key_Down)); + connect(m_syncView, &MergeView::signalNextChangedAvailable, action, &QAction::setEnabled); m_syncView->addAction(action); - action = sync1->addAction(QStringLiteral("merge_accept"),m_syncView,SLOT(mergeAccept())); - action->setText(i18nc("@action:inmenu","Copy from merging source")); + action = sync1->addAction(QStringLiteral("merge_accept"), m_syncView, SLOT(mergeAccept())); + action->setText(i18nc("@action:inmenu", "Copy from merging source")); action->setEnabled(false); - ac->setDefaultShortcut(action, QKeySequence(Qt::ALT+Qt::Key_Return)); - connect( m_syncView, &MergeView::signalEntryWithMergeDisplayed,action,&QAction::setEnabled); + ac->setDefaultShortcut(action, QKeySequence(Qt::ALT + Qt::Key_Return)); + connect(m_syncView, &MergeView::signalEntryWithMergeDisplayed, action, &QAction::setEnabled); m_syncView->addAction(action); - action = sync1->addAction(QStringLiteral("merge_acceptnew"),m_syncView,SLOT(mergeAcceptAllForEmpty())); - action->setText(i18nc("@action:inmenu","Copy all new translations")); - action->setStatusTip(i18nc("@info:status","This changes only empty and non-ready entries in base file")); + action = sync1->addAction(QStringLiteral("merge_acceptnew"), m_syncView, SLOT(mergeAcceptAllForEmpty())); + action->setText(i18nc("@action:inmenu", "Copy all new translations")); + action->setStatusTip(i18nc("@info:status", "This changes only empty and non-ready entries in base file")); action->setToolTip(action->statusTip()); action->setWhatsThis(action->statusTip()); - ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL+Qt::ALT+Qt::Key_A)); - connect( m_syncView, &MergeView::mergeCatalogAvailable,action,&QAction::setEnabled); + ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_A)); + connect(m_syncView, &MergeView::mergeCatalogAvailable, action, &QAction::setEnabled); m_syncView->addAction(action); //action->setShortcut(Qt::ALT+Qt::Key_E); - action = sync1->addAction(QStringLiteral("merge_back"),m_syncView,SLOT(mergeBack())); - action->setText(i18nc("@action:inmenu","Copy to merging source")); - connect( m_syncView, &MergeView::mergeCatalogAvailable,action,&QAction::setEnabled); - ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL+Qt::ALT+Qt::Key_Return)); + action = sync1->addAction(QStringLiteral("merge_back"), m_syncView, SLOT(mergeBack())); + action->setText(i18nc("@action:inmenu", "Copy to merging source")); + connect(m_syncView, &MergeView::mergeCatalogAvailable, action, &QAction::setEnabled); + ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_Return)); m_syncView->addAction(action); //Secondary merge - action = sync2->addAction(QStringLiteral("mergesecondary_open"),m_syncViewSecondary,SLOT(mergeOpen())); - action->setText(i18nc("@action:inmenu","Open file for secondary sync")); - action->setStatusTip(i18nc("@info:status","Open catalog to be merged into the current one / replicate base file changes to")); + action = sync2->addAction(QStringLiteral("mergesecondary_open"), m_syncViewSecondary, SLOT(mergeOpen())); + action->setText(i18nc("@action:inmenu", "Open file for secondary sync")); + action->setStatusTip(i18nc("@info:status", "Open catalog to be merged into the current one / replicate base file changes to")); action->setToolTip(action->statusTip()); action->setWhatsThis(action->statusTip()); m_syncViewSecondary->addAction(action); - action = sync2->addAction(QStringLiteral("mergesecondary_prev"),m_syncViewSecondary,SLOT(gotoPrevChanged())); - action->setText(i18nc("@action:inmenu","Previous different")); - action->setStatusTip(i18nc("@info:status","Previous entry which is translated differently in the file being merged, including empty translations in merge source")); + action = sync2->addAction(QStringLiteral("mergesecondary_prev"), m_syncViewSecondary, SLOT(gotoPrevChanged())); + action->setText(i18nc("@action:inmenu", "Previous different")); + action->setStatusTip(i18nc("@info:status", "Previous entry which is translated differently in the file being merged, including empty translations in merge source")); action->setToolTip(action->statusTip()); action->setWhatsThis(action->statusTip()); - connect( m_syncView, &MergeView::signalPriorChangedAvailable,action,&QAction::setEnabled); + connect(m_syncView, &MergeView::signalPriorChangedAvailable, action, &QAction::setEnabled); m_syncViewSecondary->addAction(action); - action = sync2->addAction(QStringLiteral("mergesecondary_next"),m_syncViewSecondary,SLOT(gotoNextChanged())); - action->setText(i18nc("@action:inmenu","Next different")); - action->setStatusTip(i18nc("@info:status","Next entry which is translated differently in the file being merged, including empty translations in merge source")); + action = sync2->addAction(QStringLiteral("mergesecondary_next"), m_syncViewSecondary, SLOT(gotoNextChanged())); + action->setText(i18nc("@action:inmenu", "Next different")); + action->setStatusTip(i18nc("@info:status", "Next entry which is translated differently in the file being merged, including empty translations in merge source")); action->setToolTip(action->statusTip()); action->setWhatsThis(action->statusTip()); - connect( m_syncView, &MergeView::signalNextChangedAvailable,action,&QAction::setEnabled); + connect(m_syncView, &MergeView::signalNextChangedAvailable, action, &QAction::setEnabled); m_syncViewSecondary->addAction(action); - action = sync2->addAction(QStringLiteral("mergesecondary_accept"),m_syncViewSecondary,SLOT(mergeAccept())); - action->setText(i18nc("@action:inmenu","Copy from merging source")); - connect( m_syncView, &MergeView::signalEntryWithMergeDisplayed,action,&QAction::setEnabled); + action = sync2->addAction(QStringLiteral("mergesecondary_accept"), m_syncViewSecondary, SLOT(mergeAccept())); + action->setText(i18nc("@action:inmenu", "Copy from merging source")); + connect(m_syncView, &MergeView::signalEntryWithMergeDisplayed, action, &QAction::setEnabled); m_syncViewSecondary->addAction(action); - action = sync2->addAction(QStringLiteral("mergesecondary_acceptnew"),m_syncViewSecondary,SLOT(mergeAcceptAllForEmpty())); - action->setText(i18nc("@action:inmenu","Copy all new translations")); - action->setStatusTip(i18nc("@info:status","This changes only empty entries")); + action = sync2->addAction(QStringLiteral("mergesecondary_acceptnew"), m_syncViewSecondary, SLOT(mergeAcceptAllForEmpty())); + action->setText(i18nc("@action:inmenu", "Copy all new translations")); + action->setStatusTip(i18nc("@info:status", "This changes only empty entries")); action->setToolTip(action->statusTip()); action->setWhatsThis(action->statusTip()); m_syncViewSecondary->addAction(action); - action = sync2->addAction(QStringLiteral("mergesecondary_back"),m_syncViewSecondary,SLOT(mergeBack())); - action->setText(i18nc("@action:inmenu","Copy to merging source")); + action = sync2->addAction(QStringLiteral("mergesecondary_back"), m_syncViewSecondary, SLOT(mergeBack())); + action->setText(i18nc("@action:inmenu", "Copy to merging source")); m_syncViewSecondary->addAction(action); } @@ -780,132 +771,125 @@ void EditorTab::setProperCaption(QString title, bool modified) { - if (m_catalog->autoSaveRecovered()) title+=' '+i18nc("editor tab name","(recovered)"); - setWindowTitle(title+QStringLiteral(" [*]")); + if (m_catalog->autoSaveRecovered()) title += ' ' + i18nc("editor tab name", "(recovered)"); + setWindowTitle(title + QStringLiteral(" [*]")); setWindowModified(modified); } void EditorTab::setFullPathShown(bool fullPathShown) { - m_fullPathShown=fullPathShown; + m_fullPathShown = fullPathShown; updateCaptionPath(); setModificationSign(); } void EditorTab::setModificationSign() { - bool clean=m_catalog->isClean() && !m_syncView->isModified() && !m_syncViewSecondary->isModified(); - setProperCaption(_captionPath,!clean); + bool clean = m_catalog->isClean() && !m_syncView->isModified() && !m_syncViewSecondary->isModified(); + setProperCaption(_captionPath, !clean); } void EditorTab::updateCaptionPath() { - QString url=m_catalog->url(); - if (!m_project->isLoaded()) - { - _captionPath=url; + QString url = m_catalog->url(); + if (!m_project->isLoaded()) { + _captionPath = url; return; } - if (!m_fullPathShown) - { - _captionPath=QFileInfo(url).fileName(); + if (!m_fullPathShown) { + _captionPath = QFileInfo(url).fileName(); return; } - _captionPath=QDir(QFileInfo(m_project->path()).absolutePath()).relativeFilePath(url); + _captionPath = QDir(QFileInfo(m_project->path()).absolutePath()).relativeFilePath(url); if (_captionPath.contains(QLatin1String("../.."))) - _captionPath=url; + _captionPath = url; else if (_captionPath.startsWith(QLatin1String("./"))) - _captionPath=_captionPath.mid(2); + _captionPath = _captionPath.mid(2); } bool EditorTab::fileOpen(QString filePath, QString suggestedDirPath, bool silent) { - if (!m_catalog->isClean()) - { + if (!m_catalog->isClean()) { switch (KMessageBox::warningYesNoCancel(SettingsController::instance()->mainWindowPtr(), - i18nc("@info","The document contains unsaved changes.\n" - "Do you want to save your changes or discard them?"),i18nc("@title:window","Warning"), - KStandardGuiItem::save(),KStandardGuiItem::discard()) - ) - { + i18nc("@info", "The document contains unsaved changes.\n" + "Do you want to save your changes or discard them?"), i18nc("@title:window", "Warning"), + KStandardGuiItem::save(), KStandardGuiItem::discard()) + ) { case KMessageBox::Yes: if (!saveFile()) return false; break; case KMessageBox::Cancel: return false; default:; } } if (suggestedDirPath.isEmpty()) - suggestedDirPath=m_catalog->url(); + suggestedDirPath = m_catalog->url(); QString saidPath; - if (filePath.isEmpty()) - { + if (filePath.isEmpty()) { //Prevent crashes //Project::instance()->model()->weaver()->suspend(); //KDE5PORT use mutex if the crash is still there with kfilemetadata library - filePath=QFileDialog::getOpenFileName(SettingsController::instance()->mainWindowPtr(), i18nc("@title:window", "Select translation file"), - suggestedDirPath, Catalog::supportedFileTypes(true));//" text/x-gettext-translation-template"); + filePath = QFileDialog::getOpenFileName(SettingsController::instance()->mainWindowPtr(), i18nc("@title:window", "Select translation file"), + suggestedDirPath, Catalog::supportedFileTypes(true));//" text/x-gettext-translation-template"); //Project::instance()->model()->weaver()->resume(); //TODO application/x-xliff, windows: just extensions //originalPath=url.path(); never used - } - else if (!QFile::exists(filePath)&&Project::instance()->isLoaded()) - { //check if we are opening template - QString newPath=filePath; - newPath.replace(Project::instance()->poDir(),Project::instance()->potDir()); - if (QFile::exists(newPath) || QFile::exists(newPath+='t')) - { - saidPath=filePath; - filePath=newPath; + } else if (!QFile::exists(filePath) && Project::instance()->isLoaded()) { + //check if we are opening template + QString newPath = filePath; + newPath.replace(Project::instance()->poDir(), Project::instance()->potDir()); + if (QFile::exists(newPath) || QFile::exists(newPath += 't')) { + saidPath = filePath; + filePath = newPath; } } if (filePath.isEmpty()) return false; QApplication::setOverrideCursor(Qt::WaitCursor); - QString prevFilePath=currentFilePath(); - bool wasOpen=!m_catalog->isEmpty(); + QString prevFilePath = currentFilePath(); + bool wasOpen = !m_catalog->isEmpty(); if (wasOpen) emit fileAboutToBeClosed(); - int errorLine=m_catalog->loadFromUrl(filePath,saidPath); - if (wasOpen&&errorLine==0) {emit fileClosed();emit fileClosed(prevFilePath);} + int errorLine = m_catalog->loadFromUrl(filePath, saidPath); + if (wasOpen && errorLine == 0) { + emit fileClosed(); + emit fileClosed(prevFilePath); + } QApplication::restoreOverrideCursor(); - if (errorLine==0) - { - statusBarItems.insert(ID_STATUS_TOTAL,i18nc("@info:status message entries","Total: %1", m_catalog->numberOfEntries())); + if (errorLine == 0) { + statusBarItems.insert(ID_STATUS_TOTAL, i18nc("@info:status message entries", "Total: %1", m_catalog->numberOfEntries())); numberOfUntranslatedChanged(); numberOfFuzziesChanged(); - m_currentPos.entry=-1;//so the signals are emitted + m_currentPos.entry = -1; //so the signals are emitted DocPosition pos(0); //we delay gotoEntry(pos) until project is loaded; //Project - if (!m_project->isLoaded()) - { + if (!m_project->isLoaded()) { QFileInfo fileInfo(filePath); #ifndef NOKDE //search for it - int i=4; - QDir dir=fileInfo.dir(); + int i = 4; + QDir dir = fileInfo.dir(); QStringList proj(QStringLiteral("*.lokalize")); dir.setNameFilters(proj); - while (--i && !dir.isRoot() && !m_project->isLoaded()) - { - if (dir.entryList().isEmpty()) {if (!dir.cdUp()) break;} - else m_project->load(dir.absoluteFilePath(dir.entryList().first())); + while (--i && !dir.isRoot() && !m_project->isLoaded()) { + if (dir.entryList().isEmpty()) { + if (!dir.cdUp()) break; + } else m_project->load(dir.absoluteFilePath(dir.entryList().first())); } #endif //enforce autosync m_syncViewSecondary->mergeOpen(filePath); - if (!m_project->isLoaded()) - { + if (!m_project->isLoaded()) { if (m_project->desirablePath().isEmpty()) - m_project->setDesirablePath(fileInfo.absolutePath()+QStringLiteral("/index.lokalize")); + m_project->setDesirablePath(fileInfo.absolutePath() + QStringLiteral("/index.lokalize")); if (m_catalog->targetLangCode().isEmpty() /*&& m_project->targetLangCode().length()*/) m_catalog->setTargetLangCode(getTargetLangCode(fileInfo.fileName())); @@ -922,97 +906,93 @@ setModificationSign(); //OK!!! - emit xliffFileOpened(m_catalog->type()==Xliff); + emit xliffFileOpened(m_catalog->type() == Xliff); emit fileOpened(); return true; } - if (!silent) - { + if (!silent) { #ifndef NOKDE - if (errorLine>0) KMessageBox::error(this, i18nc("@info","Error opening the file %1, line: %2",filePath,errorLine) ); - else KMessageBox::error(this, i18nc("@info","Error opening the file %1",filePath) ); + if (errorLine > 0) KMessageBox::error(this, i18nc("@info", "Error opening the file %1, line: %2", filePath, errorLine)); + else KMessageBox::error(this, i18nc("@info", "Error opening the file %1", filePath)); #else - KMessageBox::error(this, i18nc("@info","Error opening the file") ); + KMessageBox::error(this, i18nc("@info", "Error opening the file")); #endif } return false; } bool EditorTab::saveFileAs(const QString& defaultPath) { - QString filePath=QFileDialog::getSaveFileName(this, i18nc("@title:window", "Save File As"), - QFileInfo(defaultPath.isEmpty() ? m_catalog->url() : defaultPath).absoluteFilePath(), m_catalog->fileType()); + QString filePath = QFileDialog::getSaveFileName(this, i18nc("@title:window", "Save File As"), + QFileInfo(defaultPath.isEmpty() ? m_catalog->url() : defaultPath).absoluteFilePath(), m_catalog->fileType()); if (filePath.isEmpty()) return false; - if (!Catalog::extIsSupported(filePath)&&m_catalog->url().contains('.')) - filePath+=m_catalog->url().midRef(m_catalog->url().lastIndexOf('.')); + if (!Catalog::extIsSupported(filePath) && m_catalog->url().contains('.')) + filePath += m_catalog->url().midRef(m_catalog->url().lastIndexOf('.')); return saveFile(filePath); } bool EditorTab::saveFile(const QString& filePath) { - bool clean=m_catalog->isClean() && !m_syncView->isModified() && !m_syncViewSecondary->isModified() && filePath == m_catalog->url(); + bool clean = m_catalog->isClean() && !m_syncView->isModified() && !m_syncViewSecondary->isModified() && filePath == m_catalog->url(); if (clean) return true; - if (m_catalog->isClean() && filePath.isEmpty()) - { + if (m_catalog->isClean() && filePath.isEmpty()) { emit m_catalog->signalFileSaved(); return true; } - if (m_catalog->saveToUrl(filePath)) - { + if (m_catalog->saveToUrl(filePath)) { updateCaptionPath(); setModificationSign(); emit fileSaved(filePath); return true; } const QString errorFilePath = filePath.isEmpty() ? m_catalog->url() : filePath; #ifndef NOKDE - if ( KMessageBox::Continue==KMessageBox::warningContinueCancel(this, - i18nc("@info","Error saving the file %1\n" - "Do you want to save to another file or cancel?", errorFilePath), - i18nc("@title","Error"),KStandardGuiItem::save()) + if (KMessageBox::Continue == KMessageBox::warningContinueCancel(this, + i18nc("@info", "Error saving the file %1\n" + "Do you want to save to another file or cancel?", errorFilePath), + i18nc("@title", "Error"), KStandardGuiItem::save()) ) #else - if ( QMessageBox::Yes==QMessageBox::warning(this, QString(), - i18nc("@info","Error saving the file %1\n" - "Do you want to save to another file or cancel?").arg(errorFilePath), - QMessageBox::Yes|QMessageBox::No) + if (QMessageBox::Yes == QMessageBox::warning(this, QString(), + i18nc("@info", "Error saving the file %1\n" + "Do you want to save to another file or cancel?").arg(errorFilePath), + QMessageBox::Yes | QMessageBox::No) ) #endif return saveFileAs(errorFilePath); return false; } void EditorTab::fileAutoSaveFailedWarning(const QString& fileName) { - KMessageBox::information(this, i18nc("@info","Could not perform file autosaving.\n" - "The target file was %1.", fileName) ); + KMessageBox::information(this, i18nc("@info", "Could not perform file autosaving.\n" + "The target file was %1.", fileName)); } EditorState EditorTab::state() { EditorState state; - state.dockWidgets=saveState(); - state.filePath=m_catalog->url(); - state.mergeFilePath=m_syncView->filePath(); - state.entry=m_currentPos.entry; + state.dockWidgets = saveState(); + state.filePath = m_catalog->url(); + state.mergeFilePath = m_syncView->filePath(); + state.entry = m_currentPos.entry; //state.offset=_currentPos.offset; return state; } bool EditorTab::queryClose() { - bool clean=m_catalog->isClean() && !m_syncView->isModified() && !m_syncViewSecondary->isModified(); + bool clean = m_catalog->isClean() && !m_syncView->isModified() && !m_syncViewSecondary->isModified(); if (clean) return true; //TODO caption switch (KMessageBox::warningYesNoCancel(this, - i18nc("@info","The document contains unsaved changes.\n" - "Do you want to save your changes or discard them?"),i18nc("@title:window","Warning"), - KStandardGuiItem::save(),KStandardGuiItem::discard())) - { + i18nc("@info", "The document contains unsaved changes.\n" + "Do you want to save your changes or discard them?"), i18nc("@title:window", "Warning"), + KStandardGuiItem::save(), KStandardGuiItem::discard())) { case KMessageBox::Yes: return saveFile(); case KMessageBox::No: return true; default: return false; @@ -1022,25 +1002,24 @@ void EditorTab::undo() { - gotoEntry(m_catalog->undo(),0); + gotoEntry(m_catalog->undo(), 0); msgStrChanged(); } void EditorTab::redo() { - gotoEntry(m_catalog->redo(),0); + gotoEntry(m_catalog->redo(), 0); msgStrChanged(); } void EditorTab::gotoEntry() { - bool ok=false; - DocPosition pos=m_currentPos; - pos.entry=QInputDialog::getInt(this, i18nc("@title","Jump to Entry"), - i18nc("@label:spinbox","Enter entry number:"), - pos.entry,1,m_catalog->numberOfEntries(),1, &ok); - if (ok) - { + bool ok = false; + DocPosition pos = m_currentPos; + pos.entry = QInputDialog::getInt(this, i18nc("@title", "Jump to Entry"), + i18nc("@label:spinbox", "Enter entry number:"), + pos.entry, 1, m_catalog->numberOfEntries(), 1, &ok); + if (ok) { --(pos.entry); gotoEntry(pos); } @@ -1052,165 +1031,167 @@ void EditorTab::gotoEntry(DocPosition pos, int selection) { //specially for dbus users - if (pos.entry>=m_catalog->numberOfEntries()||pos.entry<0) + if (pos.entry >= m_catalog->numberOfEntries() || pos.entry < 0) return; if (!m_catalog->isPlural(pos)) - pos.form=0; + pos.form = 0; - m_currentPos.part=pos.part;//for searching; + m_currentPos.part = pos.part; //for searching; //UndefPart => called on fuzzy toggle - bool newEntry=m_currentPos.entry!=pos.entry || m_currentPos.form!=pos.form; - if (newEntry||pos.part==DocPosition::Comment) - { - m_notesView->gotoEntry(pos,pos.part==DocPosition::Comment?selection:0); - if (pos.part==DocPosition::Comment) - { - pos.form=0; - pos.offset=0; - selection=0; + bool newEntry = m_currentPos.entry != pos.entry || m_currentPos.form != pos.form; + if (newEntry || pos.part == DocPosition::Comment) { + m_notesView->gotoEntry(pos, pos.part == DocPosition::Comment ? selection : 0); + if (pos.part == DocPosition::Comment) { + pos.form = 0; + pos.offset = 0; + selection = 0; } } - m_view->gotoEntry(pos,selection); - if (pos.part==DocPosition::UndefPart) - m_currentPos.part=DocPosition::Target; + m_view->gotoEntry(pos, selection); + if (pos.part == DocPosition::UndefPart) + m_currentPos.part = DocPosition::Target; //QTime time; time.start(); - if (newEntry) - { - m_currentPos=pos; - if (true) - { + if (newEntry) { + m_currentPos = pos; + if (true) { emit signalNewEntryDisplayed(pos); emit entryDisplayed(); - emit signalFirstDisplayed(pos.entry==m_transUnitsView->firstEntryNumber()); - emit signalLastDisplayed(pos.entry==m_transUnitsView->lastEntryNumber()); + emit signalFirstDisplayed(pos.entry == m_transUnitsView->firstEntryNumber()); + emit signalLastDisplayed(pos.entry == m_transUnitsView->lastEntryNumber()); - emit signalPriorFuzzyAvailable(pos.entry>m_catalog->firstFuzzyIndex()); - emit signalNextFuzzyAvailable(pos.entrylastFuzzyIndex()); + emit signalPriorFuzzyAvailable(pos.entry > m_catalog->firstFuzzyIndex()); + emit signalNextFuzzyAvailable(pos.entry < m_catalog->lastFuzzyIndex()); - emit signalPriorUntranslatedAvailable(pos.entry>m_catalog->firstUntranslatedIndex()); - emit signalNextUntranslatedAvailable(pos.entrylastUntranslatedIndex()); + emit signalPriorUntranslatedAvailable(pos.entry > m_catalog->firstUntranslatedIndex()); + emit signalNextUntranslatedAvailable(pos.entry < m_catalog->lastUntranslatedIndex()); - emit signalPriorFuzzyOrUntrAvailable(pos.entry>m_catalog->firstFuzzyIndex() - ||pos.entry>m_catalog->firstUntranslatedIndex() + emit signalPriorFuzzyOrUntrAvailable(pos.entry > m_catalog->firstFuzzyIndex() + || pos.entry > m_catalog->firstUntranslatedIndex() ); - emit signalNextFuzzyOrUntrAvailable(pos.entrylastFuzzyIndex() - ||pos.entrylastUntranslatedIndex()); + emit signalNextFuzzyOrUntrAvailable(pos.entry < m_catalog->lastFuzzyIndex() + || pos.entry < m_catalog->lastUntranslatedIndex()); - emit signalPriorBookmarkAvailable(pos.entry>m_catalog->firstBookmarkIndex()); - emit signalNextBookmarkAvailable(pos.entrylastBookmarkIndex()); + emit signalPriorBookmarkAvailable(pos.entry > m_catalog->firstBookmarkIndex()); + emit signalNextBookmarkAvailable(pos.entry < m_catalog->lastBookmarkIndex()); emit signalBookmarkDisplayed(m_catalog->isBookmarked(pos.entry)); emit signalEquivTranslatedEntryDisplayed(m_catalog->isEquivTrans(pos)); emit signalApprovedEntryDisplayed(m_catalog->isApproved(pos)); } } - statusBarItems.insert(ID_STATUS_CURRENT,i18nc("@info:status","Current: %1", m_currentPos.entry+1)); + statusBarItems.insert(ID_STATUS_CURRENT, i18nc("@info:status", "Current: %1", m_currentPos.entry + 1)); //qCDebug(LOKALIZE_LOG)<<"ELA "<msgstr(m_currentPos).isEmpty(); - bool isApproved=m_catalog->isApproved(m_currentPos); - if (isUntr==m_currentIsUntr && isApproved==m_currentIsApproved) + bool isUntr = m_catalog->msgstr(m_currentPos).isEmpty(); + bool isApproved = m_catalog->isApproved(m_currentPos); + if (isUntr == m_currentIsUntr && isApproved == m_currentIsApproved) return; QString msg; - if (isUntr) msg=i18nc("@info:status","Untranslated"); - else if (isApproved)msg=i18nc("@info:status 'non-fuzzy' in gettext terminology","Ready"); - else msg=i18nc("@info:status 'fuzzy' in gettext terminology","Needs review"); + if (isUntr) msg = i18nc("@info:status", "Untranslated"); + else if (isApproved)msg = i18nc("@info:status 'non-fuzzy' in gettext terminology", "Ready"); + else msg = i18nc("@info:status 'fuzzy' in gettext terminology", "Needs review"); /* else statusBar()->changeItem("",ID_STATUS_ISFUZZY);*/ - statusBarItems.insert(ID_STATUS_ISFUZZY,msg); + statusBarItems.insert(ID_STATUS_ISFUZZY, msg); - m_currentIsUntr=isUntr; - m_currentIsApproved=isApproved; + m_currentIsUntr = isUntr; + m_currentIsApproved = isApproved; } void EditorTab::switchForm(int newForm) { - if (m_currentPos.form==newForm) return; + if (m_currentPos.form == newForm) return; - DocPosition pos=m_currentPos; - pos.form=newForm; + DocPosition pos = m_currentPos; + pos.form = newForm; gotoEntry(pos); } void EditorTab::gotoNextUnfiltered() { - DocPosition pos=m_currentPos; + DocPosition pos = m_currentPos; - if (switchNext(m_catalog,pos)) + if (switchNext(m_catalog, pos)) gotoEntry(pos); } void EditorTab::gotoPrevUnfiltered() { - DocPosition pos=m_currentPos; + DocPosition pos = m_currentPos; - if (switchPrev(m_catalog,pos)) + if (switchPrev(m_catalog, pos)) gotoEntry(pos); } -void EditorTab::gotoFirstUnfiltered(){gotoEntry(DocPosition(0));} -void EditorTab::gotoLastUnfiltered(){gotoEntry(DocPosition(m_catalog->numberOfEntries()-1));} +void EditorTab::gotoFirstUnfiltered() +{ + gotoEntry(DocPosition(0)); +} +void EditorTab::gotoLastUnfiltered() +{ + gotoEntry(DocPosition(m_catalog->numberOfEntries() - 1)); +} void EditorTab::gotoFirst() { - DocPosition pos=DocPosition(m_transUnitsView->firstEntryNumber()); - if (pos.entry!=-1) + DocPosition pos = DocPosition(m_transUnitsView->firstEntryNumber()); + if (pos.entry != -1) gotoEntry(pos); } void EditorTab::gotoLast() { - DocPosition pos=DocPosition(m_transUnitsView->lastEntryNumber()); - if (pos.entry!=-1) + DocPosition pos = DocPosition(m_transUnitsView->lastEntryNumber()); + if (pos.entry != -1) gotoEntry(pos); } void EditorTab::gotoNext() { - DocPosition pos=m_currentPos; - if (m_catalog->isPlural(pos) && pos.form+1numberOfPluralForms()) + DocPosition pos = m_currentPos; + if (m_catalog->isPlural(pos) && pos.form + 1 < m_catalog->numberOfPluralForms()) pos.form++; else - pos=DocPosition(m_transUnitsView->nextEntryNumber()); + pos = DocPosition(m_transUnitsView->nextEntryNumber()); - if (pos.entry!=-1) + if (pos.entry != -1) gotoEntry(pos); } void EditorTab::gotoPrev() { - DocPosition pos=m_currentPos; - if (m_catalog->isPlural(pos) && pos.form>0) + DocPosition pos = m_currentPos; + if (m_catalog->isPlural(pos) && pos.form > 0) pos.form--; else - pos=DocPosition(m_transUnitsView->prevEntryNumber()); + pos = DocPosition(m_transUnitsView->prevEntryNumber()); - if (pos.entry!=-1) + if (pos.entry != -1) gotoEntry(pos); } void EditorTab::gotoPrevFuzzy() { DocPosition pos; - if ( (pos.entry=m_catalog->prevFuzzyIndex(m_currentPos.entry)) == -1) + if ((pos.entry = m_catalog->prevFuzzyIndex(m_currentPos.entry)) == -1) return; gotoEntry(pos); @@ -1220,7 +1201,7 @@ { DocPosition pos; - if ( (pos.entry=m_catalog->nextFuzzyIndex(m_currentPos.entry)) == -1) + if ((pos.entry = m_catalog->nextFuzzyIndex(m_currentPos.entry)) == -1) return; gotoEntry(pos); @@ -1230,7 +1211,7 @@ { DocPosition pos; - if ( (pos.entry=m_catalog->prevUntranslatedIndex(m_currentPos.entry)) == -1) + if ((pos.entry = m_catalog->prevUntranslatedIndex(m_currentPos.entry)) == -1) return; gotoEntry(pos); @@ -1240,7 +1221,7 @@ { DocPosition pos; - if ( (pos.entry=m_catalog->nextUntranslatedIndex(m_currentPos.entry)) == -1) + if ((pos.entry = m_catalog->nextUntranslatedIndex(m_currentPos.entry)) == -1) return; gotoEntry(pos); @@ -1253,8 +1234,8 @@ short fu = m_catalog->prevFuzzyIndex(m_currentPos.entry); short un = m_catalog->prevUntranslatedIndex(m_currentPos.entry); - pos.entry=fu>un?fu:un; - if ( pos.entry == -1) + pos.entry = fu > un ? fu : un; + if (pos.entry == -1) return; gotoEntry(pos); @@ -1267,85 +1248,83 @@ bool EditorTab::gotoNextFuzzyUntr(const DocPosition& p) { - int index=(p.entry==-1)?m_currentPos.entry:p.entry; + int index = (p.entry == -1) ? m_currentPos.entry : p.entry; DocPosition pos; short fu = m_catalog->nextFuzzyIndex(index); short un = m_catalog->nextUntranslatedIndex(index); - if ( (fu == -1) && (un == -1) ) + if ((fu == -1) && (un == -1)) return false; - if (fu == -1) fu=un; - else if (un == -1) un=fu; + if (fu == -1) fu = un; + else if (un == -1) un = fu; - pos.entry=fuisApproved(m_currentPos.entry)) + if (!m_catalog->isApproved(m_currentPos.entry)) m_view->toggleApprovement(); if (!gotoNextFuzzyUntr()) gotoNextFuzzyUntr(DocPosition(-2));//so that we don't skip the first } void EditorTab::setApproveActionTitle() { - const char* const titles[]={ - I18N_NOOP2("@option:check trans-unit state","Translated"), - I18N_NOOP2("@option:check trans-unit state","Signed-off"), - I18N_NOOP2("@option:check trans-unit state","Approved") - }; - const char* const helpText[]={ - I18N_NOOP2("@info:tooltip","Translation is done (although still may need a review)"), - I18N_NOOP2("@info:tooltip","Translation has received positive review"), - I18N_NOOP2("@info:tooltip","Entry is fully localized (i.e. final)") - }; - - int role=m_catalog->activePhaseRole(); - if (role==ProjectLocal::Undefined) - role=Project::local()->role(); - m_approveAction->setText(i18nc("@option:check trans-unit state",titles[role])); - m_approveAction->setToolTip(i18nc("@info:tooltip",helpText[role])); - m_approveAndGoAction->setVisible(role==ProjectLocal::Approver); + const char* const titles[] = { + I18N_NOOP2("@option:check trans-unit state", "Translated"), + I18N_NOOP2("@option:check trans-unit state", "Signed-off"), + I18N_NOOP2("@option:check trans-unit state", "Approved") + }; + const char* const helpText[] = { + I18N_NOOP2("@info:tooltip", "Translation is done (although still may need a review)"), + I18N_NOOP2("@info:tooltip", "Translation has received positive review"), + I18N_NOOP2("@info:tooltip", "Entry is fully localized (i.e. final)") + }; + + int role = m_catalog->activePhaseRole(); + if (role == ProjectLocal::Undefined) + role = Project::local()->role(); + m_approveAction->setText(i18nc("@option:check trans-unit state", titles[role])); + m_approveAction->setToolTip(i18nc("@info:tooltip", helpText[role])); + m_approveAndGoAction->setVisible(role == ProjectLocal::Approver); #ifdef NOKDE m_stateAction->setVisible(m_catalog->capabilities()&ExtendedStates); #endif } void EditorTab::showStatesMenu() { m_stateAction->menu()->clear(); - if (!(m_catalog->capabilities()&ExtendedStates)) - { - QAction* a=m_stateAction->menu()->addAction(i18nc("@info:status 'fuzzy' in gettext terminology","Needs review")); + if (!(m_catalog->capabilities()&ExtendedStates)) { + QAction* a = m_stateAction->menu()->addAction(i18nc("@info:status 'fuzzy' in gettext terminology", "Needs review")); a->setData(QVariant(-1)); a->setCheckable(true); a->setChecked(!m_catalog->isApproved(m_currentPos)); - a=m_stateAction->menu()->addAction(i18nc("@info:status 'non-fuzzy' in gettext terminology","Ready")); + a = m_stateAction->menu()->addAction(i18nc("@info:status 'non-fuzzy' in gettext terminology", "Ready")); a->setData(QVariant(-2)); a->setCheckable(true); a->setChecked(m_catalog->isApproved(m_currentPos)); return; } - TargetState state=m_catalog->state(m_currentPos); + TargetState state = m_catalog->state(m_currentPos); - const char* const* states=Catalog::states(); - for (int i=0;imenu()->addAction(i18n(states[i])); + const char* const* states = Catalog::states(); + for (int i = 0; i < StateCount; ++i) { + QAction* a = m_stateAction->menu()->addAction(i18n(states[i])); a->setData(QVariant(i)); a->setCheckable(true); - a->setChecked(state==i); + a->setChecked(state == i); - if (i==New || i==Translated || i==Final) + if (i == New || i == Translated || i == Final) m_stateAction->menu()->addSeparator(); } } @@ -1370,7 +1349,7 @@ { DocPosition pos; - if ( (pos.entry=m_catalog->prevBookmarkIndex(m_currentPos.entry)) == -1) + if ((pos.entry = m_catalog->prevBookmarkIndex(m_currentPos.entry)) == -1) return; gotoEntry(pos); @@ -1380,7 +1359,7 @@ { DocPosition pos; - if ( (pos.entry=m_catalog->nextBookmarkIndex(m_currentPos.entry)) == -1) + if ((pos.entry = m_catalog->nextBookmarkIndex(m_currentPos.entry)) == -1) return; gotoEntry(pos); @@ -1395,10 +1374,9 @@ //HACK to prevent redundant repaintings when widget isn't visible void EditorTab::paintEvent(QPaintEvent* event) { - if (QMdiSubWindow* sw=qobject_cast(parent())) - { - if (sw->mdiArea()->currentSubWindow()!=sw) - return; + if (QMdiSubWindow* sw = qobject_cast(parent())) { + if (sw->mdiArea()->currentSubWindow() != sw) + return; } LokalizeSubwindowBase2::paintEvent(event); } @@ -1411,18 +1389,14 @@ void EditorTab::clearTranslatedEntries() { switch (KMessageBox::warningYesNoCancel(this, - i18nc("@info","This will delete all the translations from the file.\n" - "Do you really want to clear all translated entries?"),i18nc("@title:window","Warning"), - KStandardGuiItem::yes(),KStandardGuiItem::no())) - { - case KMessageBox::Yes: - { + i18nc("@info", "This will delete all the translations from the file.\n" + "Do you really want to clear all translated entries?"), i18nc("@title:window", "Warning"), + KStandardGuiItem::yes(), KStandardGuiItem::no())) { + case KMessageBox::Yes: { DocPosition pos(0); - do - { + do { removeTargetSubstring(m_catalog, pos); - } - while (switchNext(m_catalog,pos)); + } while (switchNext(m_catalog, pos)); msgStrChanged(); gotoEntry(m_currentPos); } @@ -1433,41 +1407,36 @@ void EditorTab::displayWordCount() { //TODO in trans and fuzzy separately - int sourceCount=0; - int targetCount=0; - QRegExp rxClean(Project::instance()->markup()%'|'%Project::instance()->accel());//cleaning regexp; NOTE isEmpty()? + int sourceCount = 0; + int targetCount = 0; + QRegExp rxClean(Project::instance()->markup() % '|' % Project::instance()->accel()); //cleaning regexp; NOTE isEmpty()? QRegExp rxSplit(QStringLiteral("\\W|\\d"));//splitting regexp DocPosition pos(0); - do - { - QString msg=m_catalog->source(pos); + do { + QString msg = m_catalog->source(pos); msg.remove(rxClean); - QStringList words=msg.split(rxSplit,QString::SkipEmptyParts); - sourceCount+=words.size(); + QStringList words = msg.split(rxSplit, QString::SkipEmptyParts); + sourceCount += words.size(); - msg=m_catalog->target(pos); + msg = m_catalog->target(pos); msg.remove(rxClean); - words=msg.split(rxSplit,QString::SkipEmptyParts); - targetCount+=words.size(); - } - while (switchNext(m_catalog,pos)); + words = msg.split(rxSplit, QString::SkipEmptyParts); + targetCount += words.size(); + } while (switchNext(m_catalog, pos)); KMessageBox::information(this, i18nc("@info words count", - "Source text words: %1
Target text words: %2", - sourceCount,targetCount),i18nc("@title","Word Count")); + "Source text words: %1
Target text words: %2", + sourceCount, targetCount), i18nc("@title", "Word Count")); } bool EditorTab::findEntryBySourceContext(const QString& source, const QString& ctxt) { DocPosition pos(0); - do - { - if (m_catalog->source(pos)==source && m_catalog->context(pos.entry)==QStringList(ctxt)) - { + do { + if (m_catalog->source(pos) == source && m_catalog->context(pos.entry) == QStringList(ctxt)) { gotoEntry(pos); return true; } - } - while (switchNext(m_catalog,pos)); + } while (switchNext(m_catalog, pos)); return false; } @@ -1477,20 +1446,20 @@ //TODO just a word under cursor? QString en(m_view->selectionInSource().toLower()); if (en.isEmpty()) - en=m_catalog->msgid(m_currentPos).toLower(); + en = m_catalog->msgid(m_currentPos).toLower(); QString target(m_view->selectionInTarget().toLower()); if (target.isEmpty()) - target=m_catalog->msgstr(m_currentPos).toLower(); + target = m_catalog->msgstr(m_currentPos).toLower(); - m_project->defineNewTerm(en,target); + m_project->defineNewTerm(en, target); } void EditorTab::reloadFile() { - QString mergeFilePath=m_syncView->filePath(); - DocPosition p=m_currentPos; + QString mergeFilePath = m_syncView->filePath(); + DocPosition p = m_currentPos; if (!fileOpen(currentFilePath())) return; @@ -1525,67 +1494,57 @@ } QString dir = Project::instance()->local()->sourceDir(); - if (dir.isEmpty()) - { + if (dir.isEmpty()) { switch (KMessageBox::questionYesNoCancel(SettingsController::instance()->mainWindowPtr(), - i18nc("@info","Would you like to search for the source file locally or via lxr.kde.org?"),i18nc("@title:window","Source file lookup"), - KGuiItem(i18n("Locally")), KGuiItem("lxr.kde.org") - )) - { - case KMessageBox::Yes: break; - case KMessageBox::No: openLxrSearch(srcFileRelPath); - case KMessageBox::Cancel: - default: - return; + i18nc("@info", "Would you like to search for the source file locally or via lxr.kde.org?"), i18nc("@title:window", "Source file lookup"), + KGuiItem(i18n("Locally")), KGuiItem("lxr.kde.org") + )) { + case KMessageBox::Yes: break; + case KMessageBox::No: openLxrSearch(srcFileRelPath); + case KMessageBox::Cancel: + default: + return; } } //hard fallback - if (dir.isEmpty()) - { + if (dir.isEmpty()) { dir = QFileDialog::getExistingDirectory(this, i18n("Select project's base folder for source file lookup"), QDir::homePath()); if (dir.length()) Project::instance()->local()->setSourceDir(dir); } - if (dir.length()) - { - auto doOpen = [srcFileRelPath]() - { + if (dir.length()) { + auto doOpen = [srcFileRelPath]() { auto sourceFilePaths = Project::instance()->sourceFilePaths(); bool found = false; - QByteArray fn = srcFileRelPath.midRef(srcFileRelPath.lastIndexOf('/')+1).toUtf8(); - auto it=sourceFilePaths.constFind(fn); - while (it!=sourceFilePaths.constEnd() && it.key() == fn) - { - const QString absFilePath = QString::fromUtf8(it.value()+'/'+fn); - if (!absFilePath.endsWith(srcFileRelPath) || !QFileInfo::exists(absFilePath) ) //for the case when link contained also folders - { + QByteArray fn = srcFileRelPath.midRef(srcFileRelPath.lastIndexOf('/') + 1).toUtf8(); + auto it = sourceFilePaths.constFind(fn); + while (it != sourceFilePaths.constEnd() && it.key() == fn) { + const QString absFilePath = QString::fromUtf8(it.value() + '/' + fn); + if (!absFilePath.endsWith(srcFileRelPath) || !QFileInfo::exists(absFilePath)) { //for the case when link contained also folders it++; continue; } found = true; QDesktopServices::openUrl(QUrl::fromLocalFile(absFilePath)); it++; } - if (!found) - { + if (!found) { switch (KMessageBox::warningYesNoCancel(SettingsController::instance()->mainWindowPtr(), - i18nc("@info","Could not find source file in the folder specified.\n" - "Do you want to change source files folder?"),i18nc("@title:window","Source file lookup"), - KStandardGuiItem::yes(), KStandardGuiItem::no(), KGuiItem(i18n("lxr.kde.org")))) - { - case KMessageBox::Cancel: - Project::instance()->local()->setSourceDir(QString()); - Project::instance()->resetSourceFilePaths(); - openLxrSearch(srcFileRelPath); - case KMessageBox::No: - return; - default: ; //fall through to dir selection + i18nc("@info", "Could not find source file in the folder specified.\n" + "Do you want to change source files folder?"), i18nc("@title:window", "Source file lookup"), + KStandardGuiItem::yes(), KStandardGuiItem::no(), KGuiItem(i18n("lxr.kde.org")))) { + case KMessageBox::Cancel: + Project::instance()->local()->setSourceDir(QString()); + Project::instance()->resetSourceFilePaths(); + openLxrSearch(srcFileRelPath); + case KMessageBox::No: + return; + default: ; //fall through to dir selection } QString dir = QFileDialog::getExistingDirectory(0, i18n("Select project's base folder for source file lookup"), Project::instance()->local()->sourceDir()); - if (dir.length()) - { + if (dir.length()) { Project::instance()->local()->setSourceDir(dir); Project::instance()->resetSourceFilePaths(); } @@ -1603,35 +1562,33 @@ // Otherwise, let the user know how to create a project script to handle // opening source file paths that are not relative to translation files. KMessageBox::information(this, i18nc("@info", - "Cannot open the target source file: The target source file is not " - "relative to the current translation file, and there are currently no " - "scripts loaded to handle opening source files in custom paths. Refer " - "to the Lokalize handbook for script examples and how to plug them " - "into your project.")); + "Cannot open the target source file: The target source file is not " + "relative to the current translation file, and there are currently no " + "scripts loaded to handle opening source files in custom paths. Refer " + "to the Lokalize handbook for script examples and how to plug them " + "into your project.")); } void EditorTab::mergeIntoOpenDocument() { - if (!m_catalog || m_catalog->type()!=Xliff) + if (!m_catalog || m_catalog->type() != Xliff) return; - QString xliff2odf=QStringLiteral("xliff2odf"); - if (QProcess::execute(xliff2odf, QStringList(QLatin1String("--version")))==-2) - { + QString xliff2odf = QStringLiteral("xliff2odf"); + if (QProcess::execute(xliff2odf, QStringList(QLatin1String("--version"))) == -2) { KMessageBox::error(SettingsController::instance()->mainWindowPtr(), i18n("Install translate-toolkit package and retry.")); return; } - QString xliffFolder=QFileInfo(m_catalog->url()).absolutePath(); - - QString originalOdfFilePath=m_catalog->originalOdfFilePath(); - if (originalOdfFilePath.isEmpty() || !QFile::exists(originalOdfFilePath)) - { - originalOdfFilePath=QFileDialog::getOpenFileName( - SettingsController::instance()->mainWindowPtr(), - i18n("Select original OpenDocument on which current XLIFF file is based"), - xliffFolder, - i18n("OpenDocument files (*.odt *.ods)")/*"text/x-lokalize-project"*/); + QString xliffFolder = QFileInfo(m_catalog->url()).absolutePath(); + + QString originalOdfFilePath = m_catalog->originalOdfFilePath(); + if (originalOdfFilePath.isEmpty() || !QFile::exists(originalOdfFilePath)) { + originalOdfFilePath = QFileDialog::getOpenFileName( + SettingsController::instance()->mainWindowPtr(), + i18n("Select original OpenDocument on which current XLIFF file is based"), + xliffFolder, + i18n("OpenDocument files (*.odt *.ods)")/*"text/x-lokalize-project"*/); if (originalOdfFilePath.length()) m_catalog->setOriginalOdfFilePath(originalOdfFilePath); } if (originalOdfFilePath.isEmpty()) @@ -1642,41 +1599,37 @@ //TODO check if odt did update (merge with new template is needed) QFileInfo originalOdfFileInfo(originalOdfFilePath); - QString targetLangCode=m_catalog->targetLangCode(); + QString targetLangCode = m_catalog->targetLangCode(); QStringList args(m_catalog->url()); - args.append(xliffFolder%'/'%originalOdfFileInfo.baseName()%'-'%targetLangCode%'.'%originalOdfFileInfo.suffix()); + args.append(xliffFolder % '/' % originalOdfFileInfo.baseName() % '-' % targetLangCode % '.' % originalOdfFileInfo.suffix()); args.append(QStringLiteral("-t")); args.append(originalOdfFilePath); - qCDebug(LOKALIZE_LOG)<mainWindowPtr(), i18n("Install translate-toolkit package and retry")); return; } QProcess::startDetached(lowriter, QStringList(args.at(1))); - QString reloaderScript=QStandardPaths::locate(QStandardPaths::DataLocation, QStringLiteral("scripts/odf/xliff2odf-standalone.py")); - if (reloaderScript.length()) - { - QString python=QStringLiteral("python"); + QString reloaderScript = QStandardPaths::locate(QStandardPaths::DataLocation, QStringLiteral("scripts/odf/xliff2odf-standalone.py")); + if (reloaderScript.length()) { + QString python = QStringLiteral("python"); QStringList unoArgs(QStringLiteral("-c")); unoArgs.append(QStringLiteral("import uno")); - if (QProcess::execute(python, unoArgs)!=0) - { - python=QStringLiteral("python3"); + if (QProcess::execute(python, unoArgs) != 0) { + python = QStringLiteral("python3"); QStringList unoArgs(QStringLiteral("-c")); unoArgs.append(QStringLiteral("import uno")); - if (QProcess::execute(python, unoArgs)!=0) - { + if (QProcess::execute(python, unoArgs) != 0) { KMessageBox::information(SettingsController::instance()->mainWindowPtr(), - i18n("Install python-uno package for additional functionality.")); + i18n("Install python-uno package for additional functionality.")); return; } } @@ -1697,57 +1650,116 @@ QString EditorTab::dbusObjectPath() { - const QString EDITOR_PATH=QStringLiteral("/ThisIsWhatYouWant/Editor/"); - if ( m_dbusId==-1 ) - { - m_adaptor=new EditorAdaptor(this); - - int i=0; - while(iurl();} -QByteArray EditorTab::currentFileContents(){return m_catalog->contents();} -QString EditorTab::currentEntryId(){return m_catalog->id(m_currentPos);} -QString EditorTab::selectionInTarget(){return m_view->selectionInTarget();} -QString EditorTab::selectionInSource(){return m_view->selectionInSource();} +QString EditorTab::currentFilePath() +{ + return m_catalog->url(); +} +QByteArray EditorTab::currentFileContents() +{ + return m_catalog->contents(); +} +QString EditorTab::currentEntryId() +{ + return m_catalog->id(m_currentPos); +} +QString EditorTab::selectionInTarget() +{ + return m_view->selectionInTarget(); +} +QString EditorTab::selectionInSource() +{ + return m_view->selectionInSource(); +} -void EditorTab::lookupSelectionInTranslationMemory(){emit tmLookupRequested(selectionInSource(),selectionInTarget());} +void EditorTab::lookupSelectionInTranslationMemory() +{ + emit tmLookupRequested(selectionInSource(), selectionInTarget()); +} -void EditorTab::setEntryFilteredOut(int entry, bool filteredOut){m_transUnitsView->setEntryFilteredOut(entry, filteredOut);} -void EditorTab::setEntriesFilteredOut(bool filteredOut){m_transUnitsView->setEntriesFilteredOut(filteredOut);} -int EditorTab::entryCount(){return m_catalog->numberOfEntries();} +void EditorTab::setEntryFilteredOut(int entry, bool filteredOut) +{ + m_transUnitsView->setEntryFilteredOut(entry, filteredOut); +} +void EditorTab::setEntriesFilteredOut(bool filteredOut) +{ + m_transUnitsView->setEntriesFilteredOut(filteredOut); +} +int EditorTab::entryCount() +{ + return m_catalog->numberOfEntries(); +} -QString EditorTab::entrySource(int entry, int form){return m_catalog->sourceWithTags(DocPosition(entry, form)).string;} -QString EditorTab::entryTarget(int entry, int form){return m_catalog->targetWithTags(DocPosition(entry, form)).string;} -int EditorTab::entryPluralFormCount(int entry){return m_catalog->isPlural(entry)?m_catalog->numberOfPluralForms():1;} -bool EditorTab::entryReady(int entry){return m_catalog->isApproved(entry);} -QString EditorTab::sourceLangCode(){return m_catalog->sourceLangCode();} -QString EditorTab::targetLangCode(){return m_catalog->targetLangCode();} -void EditorTab::addEntryNote(int entry, const QString& note){m_notesView->addNote(entry, note);} -void EditorTab::addTemporaryEntryNote(int entry, const QString& note){m_notesView->addTemporaryEntryNote(entry, note);} +QString EditorTab::entrySource(int entry, int form) +{ + return m_catalog->sourceWithTags(DocPosition(entry, form)).string; +} +QString EditorTab::entryTarget(int entry, int form) +{ + return m_catalog->targetWithTags(DocPosition(entry, form)).string; +} +int EditorTab::entryPluralFormCount(int entry) +{ + return m_catalog->isPlural(entry) ? m_catalog->numberOfPluralForms() : 1; +} +bool EditorTab::entryReady(int entry) +{ + return m_catalog->isApproved(entry); +} +QString EditorTab::sourceLangCode() +{ + return m_catalog->sourceLangCode(); +} +QString EditorTab::targetLangCode() +{ + return m_catalog->targetLangCode(); +} +void EditorTab::addEntryNote(int entry, const QString& note) +{ + m_notesView->addNote(entry, note); +} +void EditorTab::addTemporaryEntryNote(int entry, const QString& note) +{ + m_notesView->addTemporaryEntryNote(entry, note); +} -void EditorTab::addAlternateTranslation(int entry, const QString& translation){m_altTransView->addAlternateTranslation(entry, translation);} -void EditorTab::addTemporaryAlternateTranslation(int entry, const QString& translation){m_altTransView->addAlternateTranslation(entry, translation);} -void EditorTab::attachAlternateTranslationFile(const QString& path){m_altTransView->attachAltTransFile(path);} +void EditorTab::addAlternateTranslation(int entry, const QString& translation) +{ + m_altTransView->addAlternateTranslation(entry, translation); +} +void EditorTab::addTemporaryAlternateTranslation(int entry, const QString& translation) +{ + m_altTransView->addAlternateTranslation(entry, translation); +} +void EditorTab::attachAlternateTranslationFile(const QString& path) +{ + m_altTransView->attachAltTransFile(path); +} void EditorTab::setEntryTarget(int entry, int form, const QString& content) { - DocPosition pos(entry,form); - m_catalog->beginMacro(i18nc("@item Undo action item","Set unit text")); + DocPosition pos(entry, form); + m_catalog->beginMacro(i18nc("@item Undo action item", "Set unit text")); removeTargetSubstring(m_catalog, pos); insertCatalogString(m_catalog, pos, CatalogString(content)); m_catalog->endMacro(); - if (m_currentPos==pos) + if (m_currentPos == pos) m_view->gotoEntry(); } //END DBus interface diff --git a/src/editortab_findreplace.cpp b/src/editortab_findreplace.cpp --- a/src/editortab_findreplace.cpp +++ b/src/editortab_findreplace.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -52,55 +52,60 @@ static long makeOptions(long options, const Ui_findExtension* ui_findExtension) { return options - +IGNOREACCELS*ui_findExtension->m_ignoreAccelMarks->isChecked() - +INCLUDENOTES*ui_findExtension->m_notes->isChecked(); + + IGNOREACCELS * ui_findExtension->m_ignoreAccelMarks->isChecked() + + INCLUDENOTES * ui_findExtension->m_notes->isChecked(); //bool skipMarkup(){return ui_findExtension->m_skipTags->isChecked();} } class EntryFindDialog: public KFindDialog { public: EntryFindDialog(QWidget* parent); ~EntryFindDialog(); - long options() const{return makeOptions(KFindDialog::options(),ui_findExtension);} - static EntryFindDialog* instance(QWidget* parent=0); + long options() const + { + return makeOptions(KFindDialog::options(), ui_findExtension); + } + static EntryFindDialog* instance(QWidget* parent = 0); private: static QPointer _instance; - static void cleanup(){delete EntryFindDialog::_instance;} + static void cleanup() + { + delete EntryFindDialog::_instance; + } private: Ui_findExtension* ui_findExtension; }; -QPointer EntryFindDialog::_instance=0; +QPointer EntryFindDialog::_instance = 0; EntryFindDialog* EntryFindDialog::instance(QWidget* parent) { - if (_instance==0 ) - { - _instance=new EntryFindDialog(parent); + if (_instance == 0) { + _instance = new EntryFindDialog(parent); qAddPostRoutine(EntryFindDialog::cleanup); } return _instance; } EntryFindDialog::EntryFindDialog(QWidget* parent) - : KFindDialog(parent) - , ui_findExtension(new Ui_findExtension) + : KFindDialog(parent) + , ui_findExtension(new Ui_findExtension) { ui_findExtension->setupUi(findExtension()); setHasSelection(false); KConfig config; - KConfigGroup stateGroup(&config,"FindReplace"); - setOptions(stateGroup.readEntry("FindOptions",(qlonglong)0)); - setFindHistory(stateGroup.readEntry("FindHistory",QStringList())); + KConfigGroup stateGroup(&config, "FindReplace"); + setOptions(stateGroup.readEntry("FindOptions", (qlonglong)0)); + setFindHistory(stateGroup.readEntry("FindHistory", QStringList())); } EntryFindDialog::~EntryFindDialog() { KConfig config; - KConfigGroup stateGroup(&config,"FindReplace"); - stateGroup.writeEntry("FindOptions",(qlonglong)options()); - stateGroup.writeEntry("FindHistory",findHistory()); + KConfigGroup stateGroup(&config, "FindReplace"); + stateGroup.writeEntry("FindOptions", (qlonglong)options()); + stateGroup.writeEntry("FindHistory", findHistory()); delete ui_findExtension; } @@ -111,83 +116,84 @@ public: EntryReplaceDialog(QWidget* parent); ~EntryReplaceDialog(); - long options() const{return makeOptions(KReplaceDialog::options(),ui_findExtension);} - static EntryReplaceDialog* instance(QWidget* parent=0); + long options() const + { + return makeOptions(KReplaceDialog::options(), ui_findExtension); + } + static EntryReplaceDialog* instance(QWidget* parent = 0); private: static QPointer _instance; - static void cleanup(){delete EntryReplaceDialog::_instance;} + static void cleanup() + { + delete EntryReplaceDialog::_instance; + } private: Ui_findExtension* ui_findExtension; }; -QPointer EntryReplaceDialog::_instance=0; +QPointer EntryReplaceDialog::_instance = 0; EntryReplaceDialog* EntryReplaceDialog::instance(QWidget* parent) { - if (_instance==0 ) - { - _instance=new EntryReplaceDialog(parent); + if (_instance == 0) { + _instance = new EntryReplaceDialog(parent); qAddPostRoutine(EntryReplaceDialog::cleanup); } return _instance; } EntryReplaceDialog::EntryReplaceDialog(QWidget* parent) - : KReplaceDialog(parent) - , ui_findExtension(new Ui_findExtension) + : KReplaceDialog(parent) + , ui_findExtension(new Ui_findExtension) { ui_findExtension->setupUi(findExtension()); //ui_findExtension->m_notes->hide(); setHasSelection(false); KConfig config; - KConfigGroup stateGroup(&config,"FindReplace"); - setOptions(stateGroup.readEntry("ReplaceOptions",(qlonglong)0)); - setFindHistory(stateGroup.readEntry("ReplacePatternHistory",QStringList())); - setReplacementHistory(stateGroup.readEntry("ReplacementHistory",QStringList())); + KConfigGroup stateGroup(&config, "FindReplace"); + setOptions(stateGroup.readEntry("ReplaceOptions", (qlonglong)0)); + setFindHistory(stateGroup.readEntry("ReplacePatternHistory", QStringList())); + setReplacementHistory(stateGroup.readEntry("ReplacementHistory", QStringList())); } EntryReplaceDialog::~EntryReplaceDialog() { KConfig config; - KConfigGroup stateGroup(&config,"FindReplace"); - stateGroup.writeEntry("ReplaceOptions",(qlonglong)options()); - stateGroup.writeEntry("ReplacePatternHistory",findHistory()); - stateGroup.writeEntry("ReplacementHistory",replacementHistory()); + KConfigGroup stateGroup(&config, "FindReplace"); + stateGroup.writeEntry("ReplaceOptions", (qlonglong)options()); + stateGroup.writeEntry("ReplacePatternHistory", findHistory()); + stateGroup.writeEntry("ReplacementHistory", replacementHistory()); delete ui_findExtension; } //END EntryReplaceDialog //TODO &,   static void calcOffsetWithAccels(const QString& data, int& offset, int& length) { - int i=0; - for (;ioptions() & KFind::FindBackwards) - { - pos.entry=m_catalog->numberOfEntries()-1; - pos.form=(m_catalog->isPlural(pos.entry))? - m_catalog->numberOfPluralForms()-1:0; - } - else - { - pos.entry=0; - pos.form=0; + if (find->options() & KFind::FindBackwards) { + pos.entry = m_catalog->numberOfEntries() - 1; + pos.form = (m_catalog->isPlural(pos.entry)) ? + m_catalog->numberOfPluralForms() - 1 : 0; + } else { + pos.entry = 0; + pos.form = 0; } return true; } @@ -197,180 +203,162 @@ //QWidget* p=0; QWidget* next=qobject_cast(parent()); while(next) { p=next; next=qobject_cast(next->parent()); } EntryFindDialog::instance(nativeParentWidget()); - QString sel=selectionInTarget(); - if (!(sel.isEmpty()&&selectionInSource().isEmpty())) - { + QString sel = selectionInTarget(); + if (!(sel.isEmpty() && selectionInSource().isEmpty())) { if (sel.isEmpty()) - sel=selectionInSource(); - if (m_find&&m_find->options()&IGNOREACCELS) + sel = selectionInSource(); + if (m_find && m_find->options()&IGNOREACCELS) sel.remove('&'); EntryFindDialog::instance()->setPattern(sel); } - if ( EntryFindDialog::instance()->exec() != QDialog::Accepted ) + if (EntryFindDialog::instance()->exec() != QDialog::Accepted) return; - if (m_find) - { + if (m_find) { m_find->resetCounts(); m_find->setPattern(EntryFindDialog::instance()->pattern()); m_find->setOptions(EntryFindDialog::instance()->options()); - } - else // This creates a find-next-prompt dialog if needed. - { - m_find = new KFind(EntryFindDialog::instance()->pattern(),EntryFindDialog::instance()->options(),this,EntryFindDialog::instance()); + } else { // This creates a find-next-prompt dialog if needed. + m_find = new KFind(EntryFindDialog::instance()->pattern(), EntryFindDialog::instance()->options(), this, EntryFindDialog::instance()); connect(m_find, QOverload::of(&KFind::highlight), this, &EditorTab::highlightFound); connect(m_find, &KFind::findNext, this, QOverload<>::of(&EditorTab::findNext)); m_find->closeFindNextDialog(); } DocPosition pos; if (m_find->options() & KFind::FromCursor) - pos=m_currentPos; + pos = m_currentPos; else if (!determineStartingPos(m_catalog, m_find, pos)) - return; + return; findNext(pos); } void EditorTab::findNext(const DocPosition& startingPos) { - Catalog& catalog=*m_catalog; - KFind& find=*m_find; + Catalog& catalog = *m_catalog; + KFind& find = *m_find; - if (Q_UNLIKELY( catalog.numberOfEntries()<=startingPos.entry )) + if (Q_UNLIKELY(catalog.numberOfEntries() <= startingPos.entry)) return;//for the case when app wasn't able to process event before file close - bool anotherEntry=_searchingPos.entry!=m_currentPos.entry; - _searchingPos=startingPos; + bool anotherEntry = _searchingPos.entry != m_currentPos.entry; + _searchingPos = startingPos; if (anotherEntry) - _searchingPos.offset=0; + _searchingPos.offset = 0; QRegExp rx("[^(\\\\n)>]\n"); - QTime a;a.start(); + QTime a; a.start(); //_searchingPos.part=DocPosition::Source; - bool ignoreaccels=m_find->options()&IGNOREACCELS; - bool includenotes=m_find->options()&INCLUDENOTES; - int switchOptions=DocPosition::Source|DocPosition::Target|(includenotes*DocPosition::Comment); - int flag=1; - while (flag) - { + bool ignoreaccels = m_find->options()&IGNOREACCELS; + bool includenotes = m_find->options()&INCLUDENOTES; + int switchOptions = DocPosition::Source | DocPosition::Target | (includenotes * DocPosition::Comment); + int flag = 1; + while (flag) { - flag=0; + flag = 0; KFind::Result res = KFind::NoMatch; - while (true) - { - if (find.needData()||anotherEntry||m_view->m_modifiedAfterFind) - { - anotherEntry=false; - m_view->m_modifiedAfterFind=false; + while (true) { + if (find.needData() || anotherEntry || m_view->m_modifiedAfterFind) { + anotherEntry = false; + m_view->m_modifiedAfterFind = false; QString data; - if (_searchingPos.part==DocPosition::Comment) - data=catalog.notes(_searchingPos).at(_searchingPos.form).content; + if (_searchingPos.part == DocPosition::Comment) + data = catalog.notes(_searchingPos).at(_searchingPos.form).content; else - data=catalog.catalogString(_searchingPos).string; + data = catalog.catalogString(_searchingPos).string; if (ignoreaccels) data.remove('&'); find.setData(data); } res = find.find(); //offset=-1; - if (res!=KFind::NoMatch) + if (res != KFind::NoMatch) break; if (!( - (find.options()&KFind::FindBackwards)? - switchPrev(m_catalog,_searchingPos,switchOptions): - switchNext(m_catalog,_searchingPos,switchOptions) - )) + (find.options()&KFind::FindBackwards) ? + switchPrev(m_catalog, _searchingPos, switchOptions) : + switchNext(m_catalog, _searchingPos, switchOptions) + )) break; } - if (res==KFind::NoMatch) - { + if (res == KFind::NoMatch) { //file-wide search - if(find.shouldRestart(true,true)) - { - flag=1; - determineStartingPos(m_catalog, m_find,_searchingPos); + if (find.shouldRestart(true, true)) { + flag = 1; + determineStartingPos(m_catalog, m_find, _searchingPos); } find.resetCounts(); } } } void EditorTab::findNext() { - if (m_find) - { - findNext((m_currentPos.entry==_searchingPos.entry&&_searchingPos.part==DocPosition::Comment)? - _searchingPos:m_currentPos); - } - else + if (m_find) { + findNext((m_currentPos.entry == _searchingPos.entry && _searchingPos.part == DocPosition::Comment) ? + _searchingPos : m_currentPos); + } else find(); } void EditorTab::findPrev() { - if (m_find) - { + if (m_find) { m_find->setOptions(m_find->options() ^ KFind::FindBackwards); findNext(m_currentPos); - } - else - { + } else { find(); } } -void EditorTab::highlightFound(const QString &,int matchingIndex,int matchedLength) +void EditorTab::highlightFound(const QString &, int matchingIndex, int matchedLength) { - if (m_find->options()&IGNOREACCELS && _searchingPos.part!=DocPosition::Comment) - { - QString data=m_catalog->catalogString(_searchingPos).string; + if (m_find->options()&IGNOREACCELS && _searchingPos.part != DocPosition::Comment) { + QString data = m_catalog->catalogString(_searchingPos).string; calcOffsetWithAccels(data, matchingIndex, matchedLength); } - _searchingPos.offset=matchingIndex; - gotoEntry(_searchingPos,matchedLength); + _searchingPos.offset = matchingIndex; + gotoEntry(_searchingPos, matchedLength); } void EditorTab::replace() { EntryReplaceDialog::instance(nativeParentWidget()); - if (!m_view->selectionInTarget().isEmpty()) - { - if (m_replace&&m_replace->options()&IGNOREACCELS) - { + if (!m_view->selectionInTarget().isEmpty()) { + if (m_replace && m_replace->options()&IGNOREACCELS) { QString tmp(m_view->selectionInTarget()); tmp.remove('&'); EntryReplaceDialog::instance()->setPattern(tmp); - } - else + } else EntryReplaceDialog::instance()->setPattern(m_view->selectionInTarget()); } - if ( EntryReplaceDialog::instance()->exec() != QDialog::Accepted ) + if (EntryReplaceDialog::instance()->exec() != QDialog::Accepted) return; if (m_replace) m_replace->deleteLater();// _replace=0; // This creates a find-next-prompt dialog if needed. { - m_replace = new KReplace(EntryReplaceDialog::instance()->pattern(),EntryReplaceDialog::instance()->replacement(),EntryReplaceDialog::instance()->options(),this,EntryReplaceDialog::instance()); + m_replace = new KReplace(EntryReplaceDialog::instance()->pattern(), EntryReplaceDialog::instance()->replacement(), EntryReplaceDialog::instance()->options(), this, EntryReplaceDialog::instance()); connect(m_replace, QOverload::of(&KReplace::highlight), this, &EditorTab::highlightFound_); connect(m_replace, &KReplace::findNext, this, QOverload<>::of(&EditorTab::replaceNext)); connect(m_replace, QOverload::of(&KReplace::replace), this, &EditorTab::doReplace); @@ -385,79 +373,70 @@ // } //m_catalog->beginMacro(i18nc("@item Undo action item","Replace")); - m_doReplaceCalled=false; + m_doReplaceCalled = false; if (m_replace->options() & KFind::FromCursor) replaceNext(m_currentPos); - else - { + else { DocPosition pos; - if (!determineStartingPos(m_catalog, m_replace,pos)) return; + if (!determineStartingPos(m_catalog, m_replace, pos)) return; replaceNext(pos); } } void EditorTab::replaceNext(const DocPosition& startingPos) { - bool anotherEntry=m_currentPos.entry!=_replacingPos.entry; - _replacingPos=startingPos; + bool anotherEntry = m_currentPos.entry != _replacingPos.entry; + _replacingPos = startingPos; if (anotherEntry) - _replacingPos.offset=0; + _replacingPos.offset = 0; - int flag=1; - bool ignoreaccels=m_replace->options()&IGNOREACCELS; - bool includenotes=m_replace->options()&INCLUDENOTES; - qCWarning(LOKALIZE_LOG)<<"includenotes"<needData()||anotherEntry/*||m_view->m_modifiedAfterFind*/) - { - anotherEntry=false; + int flag = 1; + bool ignoreaccels = m_replace->options()&IGNOREACCELS; + bool includenotes = m_replace->options()&INCLUDENOTES; + qCWarning(LOKALIZE_LOG) << "includenotes" << includenotes; + int switchOptions = DocPosition::Target | (includenotes * DocPosition::Comment); + while (flag) { + flag = 0; + KFind::Result res = KFind::NoMatch; + while (1) { + if (m_replace->needData() || anotherEntry/*||m_view->m_modifiedAfterFind*/) { + anotherEntry = false; //m_view->m_modifiedAfterFind=false;//NOTE TEST THIS QString data; - if (_replacingPos.part==DocPosition::Comment) - data=m_catalog->notes(_replacingPos).at(_replacingPos.form).content; - else - { - data=m_catalog->targetWithTags(_replacingPos).string; + if (_replacingPos.part == DocPosition::Comment) + data = m_catalog->notes(_replacingPos).at(_replacingPos.form).content; + else { + data = m_catalog->targetWithTags(_replacingPos).string; if (ignoreaccels) data.remove('&'); } m_replace->setData(data); } res = m_replace->replace(); - if (res!=KFind::NoMatch) + if (res != KFind::NoMatch) break; if (!( - (m_replace->options()&KFind::FindBackwards)? - switchPrev(m_catalog,_replacingPos,switchOptions): - switchNext(m_catalog,_replacingPos,switchOptions) - )) + (m_replace->options()&KFind::FindBackwards) ? + switchPrev(m_catalog, _replacingPos, switchOptions) : + switchNext(m_catalog, _replacingPos, switchOptions) + )) break; } - if (res==KFind::NoMatch) - { - if((m_replace->options()&KFind::FromCursor) - &&m_replace->shouldRestart(true)) - { - flag=1; - determineStartingPos(m_catalog, m_replace,_replacingPos); - } - else - { - if(!(m_replace->options() & KFind::FromCursor)) - m_replace->displayFinalDialog(); + if (res == KFind::NoMatch) { + if ((m_replace->options()&KFind::FromCursor) + && m_replace->shouldRestart(true)) { + flag = 1; + determineStartingPos(m_catalog, m_replace, _replacingPos); + } else { + if (!(m_replace->options() & KFind::FromCursor)) + m_replace->displayFinalDialog(); m_replace->closeReplaceNextDialog(); cleanupReplace(); @@ -469,9 +448,8 @@ void EditorTab::cleanupReplace() { - if(m_doReplaceCalled) - { - m_doReplaceCalled=false; + if (m_doReplaceCalled) { + m_doReplaceCalled = false; m_catalog->endMacro(); } } @@ -481,80 +459,75 @@ replaceNext(m_currentPos); } -void EditorTab::highlightFound_(const QString &,int matchingIndex,int matchedLength) +void EditorTab::highlightFound_(const QString &, int matchingIndex, int matchedLength) { - if (m_replace->options()&IGNOREACCELS) - { - QString data=m_catalog->targetWithTags(_replacingPos).string; - calcOffsetWithAccels(data,matchingIndex,matchedLength); + if (m_replace->options()&IGNOREACCELS) { + QString data = m_catalog->targetWithTags(_replacingPos).string; + calcOffsetWithAccels(data, matchingIndex, matchedLength); } - _replacingPos.offset=matchingIndex; - gotoEntry(_replacingPos,matchedLength); + _replacingPos.offset = matchingIndex; + gotoEntry(_replacingPos, matchedLength); } -void EditorTab::doReplace(const QString &newStr,int offset,int newLen,int remLen) +void EditorTab::doReplace(const QString &newStr, int offset, int newLen, int remLen) { - if(!m_doReplaceCalled) - { - m_doReplaceCalled=true; - m_catalog->beginMacro(i18nc("@item Undo action item","Replace")); + if (!m_doReplaceCalled) { + m_doReplaceCalled = true; + m_catalog->beginMacro(i18nc("@item Undo action item", "Replace")); } - DocPosition pos=_replacingPos; - if (_replacingPos.part==DocPosition::Comment) - m_catalog->push(new SetNoteCmd(m_catalog,pos,newStr)); - else - { - QString oldStr=m_catalog->target(_replacingPos); + DocPosition pos = _replacingPos; + if (_replacingPos.part == DocPosition::Comment) + m_catalog->push(new SetNoteCmd(m_catalog, pos, newStr)); + else { + QString oldStr = m_catalog->target(_replacingPos); if (m_replace->options()&IGNOREACCELS) - calcOffsetWithAccels(oldStr,offset,remLen); + calcOffsetWithAccels(oldStr, offset, remLen); - pos.offset=offset; - m_catalog->push(new DelTextCmd(m_catalog,pos,oldStr.mid(offset,remLen))); + pos.offset = offset; + m_catalog->push(new DelTextCmd(m_catalog, pos, oldStr.mid(offset, remLen))); if (newLen) - m_catalog->push(new InsTextCmd(m_catalog,pos,newStr.mid(offset,newLen))); + m_catalog->push(new InsTextCmd(m_catalog, pos, newStr.mid(offset, newLen))); } - if (pos.entry==m_currentPos.entry) - { - pos.offset+=newLen; + if (pos.entry == m_currentPos.entry) { + pos.offset += newLen; m_view->gotoEntry(pos, 0); } } void EditorTab::spellcheck() { - if (!m_sonnetDialog) - { - m_sonnetChecker=new Sonnet::BackgroundChecker(this); + if (!m_sonnetDialog) { + m_sonnetChecker = new Sonnet::BackgroundChecker(this); m_sonnetChecker->changeLanguage(enhanceLangCode(Project::instance()->langCode())); - m_sonnetDialog=new Sonnet::Dialog(m_sonnetChecker,this); + m_sonnetDialog = new Sonnet::Dialog(m_sonnetChecker, this); connect(m_sonnetDialog, QOverload::of(&Sonnet::Dialog::done), this, &EditorTab::spellcheckNext); connect(m_sonnetDialog, &Sonnet::Dialog::replace, this, &EditorTab::spellcheckReplace); connect(m_sonnetDialog, &Sonnet::Dialog::stop, this, &EditorTab::spellcheckStop); connect(m_sonnetDialog, &Sonnet::Dialog::cancel, this, &EditorTab::spellcheckCancel); connect(m_sonnetDialog/*m_sonnetChecker*/, &Sonnet::Dialog::misspelling, this, &EditorTab::spellcheckShow); // disconnect(/*m_sonnetDialog*/m_sonnetChecker,SIGNAL(misspelling(QString,int)), // m_sonnetDialog,SLOT(slotMisspelling(QString,int))); -// +// // connect( d->checker, SIGNAL(misspelling(const QString&, int)), // SLOT(slotMisspelling(const QString&, int)) ); } - QString text=m_catalog->msgstr(m_currentPos); + QString text = m_catalog->msgstr(m_currentPos); if (!m_view->selectionInTarget().isEmpty()) - text=m_view->selectionInTarget(); + text = m_view->selectionInTarget(); text.remove('&'); m_sonnetDialog->setBuffer(text); - _spellcheckPos=m_currentPos; - _spellcheckStartPos=m_currentPos; - m_spellcheckStop=false; + _spellcheckPos = m_currentPos; + _spellcheckStartPos = m_currentPos; + m_spellcheckStop = false; //m_catalog->beginMacro(i18n("Spellcheck")); - m_spellcheckStartUndoIndex=m_catalog->index(); + m_spellcheckStartUndoIndex = m_catalog->index(); m_sonnetDialog->show(); } @@ -565,37 +538,31 @@ if (m_spellcheckStop) return; - do - { - if (!switchNext(m_catalog,_spellcheckPos)) - { - qCWarning(LOKALIZE_LOG)<<_spellcheckStartPos.entry; - qCWarning(LOKALIZE_LOG)<<_spellcheckStartPos.form; - bool continueFromStart= - !(_spellcheckStartPos.entry==0 && _spellcheckStartPos.form==0) - && KMessageBox::questionYesNo(this,i18n("Lokalize has reached end of document. Do you want to continue from start?"), - i18nc("@title", "Spellcheck"))==KMessageBox::Yes; - if (continueFromStart) - { - _spellcheckStartPos.entry=0; - _spellcheckStartPos.form=0; - _spellcheckPos=_spellcheckStartPos; - } - else - { - KMessageBox::information(this,i18n("Lokalize has finished spellchecking"), i18nc("@title", "Spellcheck")); + do { + if (!switchNext(m_catalog, _spellcheckPos)) { + qCWarning(LOKALIZE_LOG) << _spellcheckStartPos.entry; + qCWarning(LOKALIZE_LOG) << _spellcheckStartPos.form; + bool continueFromStart = + !(_spellcheckStartPos.entry == 0 && _spellcheckStartPos.form == 0) + && KMessageBox::questionYesNo(this, i18n("Lokalize has reached end of document. Do you want to continue from start?"), + i18nc("@title", "Spellcheck")) == KMessageBox::Yes; + if (continueFromStart) { + _spellcheckStartPos.entry = 0; + _spellcheckStartPos.form = 0; + _spellcheckPos = _spellcheckStartPos; + } else { + KMessageBox::information(this, i18n("Lokalize has finished spellchecking"), i18nc("@title", "Spellcheck")); return; } } - } - while (m_catalog->msgstr(_spellcheckPos).isEmpty() || !m_catalog->isApproved(_spellcheckPos.entry)); + } while (m_catalog->msgstr(_spellcheckPos).isEmpty() || !m_catalog->isApproved(_spellcheckPos.entry)); m_sonnetDialog->setBuffer(m_catalog->msgstr(_spellcheckPos).remove(Project::instance()->accel())); } void EditorTab::spellcheckStop() { - m_spellcheckStop=true; + m_spellcheckStop = true; } void EditorTab::spellcheckCancel() @@ -609,10 +576,9 @@ const Project& project = *Project::instance(); const QString accel = project.accel(); - QString source=m_catalog->source(_spellcheckPos); + QString source = m_catalog->source(_spellcheckPos); source.remove(accel); - if (source.contains(word) && project.targetLangCode().leftRef(2) != project.sourceLangCode().leftRef(2)) - { + if (source.contains(word) && project.targetLangCode().leftRef(2) != project.sourceLangCode().leftRef(2)) { m_sonnetDialog->setUpdatesEnabled(false); m_sonnetChecker->continueChecking(); return; @@ -622,28 +588,28 @@ show(); - DocPosition pos=_spellcheckPos; - int length=word.length(); - calcOffsetWithAccels(m_catalog->target(pos),offset,length); - pos.offset=offset; + DocPosition pos = _spellcheckPos; + int length = word.length(); + calcOffsetWithAccels(m_catalog->target(pos), offset, length); + pos.offset = offset; - gotoEntry(pos,length); + gotoEntry(pos, length); } void EditorTab::spellcheckReplace(QString oldWord, int offset, const QString &newWord) { - DocPosition pos=_spellcheckPos; - int length=oldWord.length(); - calcOffsetWithAccels(m_catalog->target(pos),offset,length); - pos.offset=offset; - if (length>oldWord.length())//replaced word contains accel mark - oldWord=m_catalog->target(pos).mid(offset,length); + DocPosition pos = _spellcheckPos; + int length = oldWord.length(); + calcOffsetWithAccels(m_catalog->target(pos), offset, length); + pos.offset = offset; + if (length > oldWord.length()) //replaced word contains accel mark + oldWord = m_catalog->target(pos).mid(offset, length); - m_catalog->push(new DelTextCmd(m_catalog,pos,oldWord)); - m_catalog->push(new InsTextCmd(m_catalog,pos,newWord)); + m_catalog->push(new DelTextCmd(m_catalog, pos, oldWord)); + m_catalog->push(new InsTextCmd(m_catalog, pos, newWord)); - gotoEntry(pos,newWord.length()); + gotoEntry(pos, newWord.length()); } diff --git a/src/editorview.h b/src/editorview.h --- a/src/editorview.h +++ b/src/editorview.h @@ -55,10 +55,13 @@ { Q_OBJECT public: - EditorView(QWidget *,Catalog*); + EditorView(QWidget *, Catalog*); virtual ~EditorView(); - QTabBar* tabBar(){return m_pluralTabBar;}//to connect tabbar signals to controller (EditorWindow) slots + QTabBar* tabBar() + { + return m_pluralTabBar; //to connect tabbar signals to controller (EditorWindow) slots + } QString selectionInTarget() const;//for non-batch replace QString selectionInSource() const; @@ -78,16 +81,16 @@ void unwrap(); void unwrap(TranslationUnitTextEdit* editor); -/* - void dragEnterEvent(QDragEnterEvent* event); - void dropEvent(QDropEvent*); -*/ + /* + void dragEnterEvent(QDragEnterEvent* event); + void dropEvent(QDropEvent*); + */ private: Catalog* m_catalog; TranslationUnitTextEdit * m_sourceTextEdit; TranslationUnitTextEdit * m_targetTextEdit -; + ; QTabBar* m_pluralTabBar; LedsWidget* m_leds; @@ -118,9 +121,9 @@ #ifndef NOKDE class KLed; class QLabel; -class LedsWidget:public QWidget +class LedsWidget: public QWidget { -Q_OBJECT + Q_OBJECT public: LedsWidget(QWidget* parent); private: diff --git a/src/editorview.cpp b/src/editorview.cpp --- a/src/editorview.cpp +++ b/src/editorview.cpp @@ -66,26 +66,26 @@ { KColorScheme colorScheme(QPalette::Normal); - QHBoxLayout* layout=new QHBoxLayout(this); + QHBoxLayout* layout = new QHBoxLayout(this); layout->addStretch(); - layout->addWidget(new QLabel(i18nc("@label whether entry is fuzzy","Not ready:"),this)); - layout->addWidget(ledFuzzy=new KLed(colorScheme.foreground(KColorScheme::NeutralText).color()/*Qt::green*/,KLed::Off,KLed::Sunken,KLed::Rectangular)); - layout->addWidget(new QLabel(i18nc("@label whether entry is untranslated","Untranslated:"),this)); - layout->addWidget(ledUntr=new KLed(colorScheme.foreground(KColorScheme::NegativeText).color()/*Qt::red*/,KLed::Off,KLed::Sunken,KLed::Rectangular)); + layout->addWidget(new QLabel(i18nc("@label whether entry is fuzzy", "Not ready:"), this)); + layout->addWidget(ledFuzzy = new KLed(colorScheme.foreground(KColorScheme::NeutralText).color()/*Qt::green*/, KLed::Off, KLed::Sunken, KLed::Rectangular)); + layout->addWidget(new QLabel(i18nc("@label whether entry is untranslated", "Untranslated:"), this)); + layout->addWidget(ledUntr = new KLed(colorScheme.foreground(KColorScheme::NegativeText).color()/*Qt::red*/, KLed::Off, KLed::Sunken, KLed::Rectangular)); layout->addSpacing(1); - layout->addWidget(lblColumn=new QLabel(this)); + layout->addWidget(lblColumn = new QLabel(this)); layout->addStretch(); setMaximumHeight(minimumSizeHint().height()); } void LedsWidget::contextMenuEvent(QContextMenuEvent* event) { QMenu menu; - menu.addAction(i18nc("@action","Hide")); + menu.addAction(i18nc("@action", "Hide")); if (!menu.exec(event->globalPos())) return; //NOTE the config doesn't seem to work Settings::setLeds(false); - SettingsController::instance()->dirty=true; + SettingsController::instance()->dirty = true; hide(); } @@ -96,52 +96,52 @@ #endif -EditorView::EditorView(QWidget *parent,Catalog* catalog/*,keyEventHandler* kh*/) - : QSplitter(Qt::Vertical,parent) +EditorView::EditorView(QWidget *parent, Catalog* catalog/*,keyEventHandler* kh*/) + : QSplitter(Qt::Vertical, parent) , m_catalog(catalog) - , m_sourceTextEdit(new TranslationUnitTextEdit(catalog,DocPosition::Source,this)) - , m_targetTextEdit(new TranslationUnitTextEdit(catalog,DocPosition::Target,this)) + , m_sourceTextEdit(new TranslationUnitTextEdit(catalog, DocPosition::Source, this)) + , m_targetTextEdit(new TranslationUnitTextEdit(catalog, DocPosition::Target, this)) , m_pluralTabBar(new QTabBar(this)) #ifndef NOKDE , m_leds(0) #endif , m_modifiedAfterFind(false) { m_pluralTabBar->hide(); m_sourceTextEdit->setWhatsThis(i18n("

Original String

\n" - "

This part of the window shows the original message\n" - "of the currently displayed entry.

")); + "

This part of the window shows the original message\n" + "of the currently displayed entry.

")); m_sourceTextEdit->viewport()->setBackgroundRole(QPalette::Background); - connect (m_targetTextEdit, &TranslationUnitTextEdit::contentsModified, this, &EditorView::resetFindForCurrent); - connect (m_targetTextEdit, &TranslationUnitTextEdit::toggleApprovementRequested, this, &EditorView::toggleApprovement); - connect (this, &EditorView::signalApprovedEntryDisplayed, m_targetTextEdit, &TranslationUnitTextEdit::reflectApprovementState); - connect (m_sourceTextEdit, &TranslationUnitTextEdit::tagInsertRequested, m_targetTextEdit, &TranslationUnitTextEdit::insertTag); + connect(m_targetTextEdit, &TranslationUnitTextEdit::contentsModified, this, &EditorView::resetFindForCurrent); + connect(m_targetTextEdit, &TranslationUnitTextEdit::toggleApprovementRequested, this, &EditorView::toggleApprovement); + connect(this, &EditorView::signalApprovedEntryDisplayed, m_targetTextEdit, &TranslationUnitTextEdit::reflectApprovementState); + connect(m_sourceTextEdit, &TranslationUnitTextEdit::tagInsertRequested, m_targetTextEdit, &TranslationUnitTextEdit::insertTag); - connect (m_sourceTextEdit, &TranslationUnitTextEdit::binaryUnitSelectRequested, this, &EditorView::binaryUnitSelectRequested); - connect (m_targetTextEdit, &TranslationUnitTextEdit::binaryUnitSelectRequested, this, &EditorView::binaryUnitSelectRequested); - connect (m_sourceTextEdit, &TranslationUnitTextEdit::gotoEntryRequested, this, &EditorView::gotoEntryRequested); - connect (m_targetTextEdit, &TranslationUnitTextEdit::gotoEntryRequested, this, &EditorView::gotoEntryRequested); + connect(m_sourceTextEdit, &TranslationUnitTextEdit::binaryUnitSelectRequested, this, &EditorView::binaryUnitSelectRequested); + connect(m_targetTextEdit, &TranslationUnitTextEdit::binaryUnitSelectRequested, this, &EditorView::binaryUnitSelectRequested); + connect(m_sourceTextEdit, &TranslationUnitTextEdit::gotoEntryRequested, this, &EditorView::gotoEntryRequested); + connect(m_targetTextEdit, &TranslationUnitTextEdit::gotoEntryRequested, this, &EditorView::gotoEntryRequested); - connect (m_sourceTextEdit, &TranslationUnitTextEdit::tmLookupRequested, this, &EditorView::tmLookupRequested); - connect (m_targetTextEdit, &TranslationUnitTextEdit::tmLookupRequested, this, &EditorView::tmLookupRequested); + connect(m_sourceTextEdit, &TranslationUnitTextEdit::tmLookupRequested, this, &EditorView::tmLookupRequested); + connect(m_targetTextEdit, &TranslationUnitTextEdit::tmLookupRequested, this, &EditorView::tmLookupRequested); - connect (m_sourceTextEdit, &TranslationUnitTextEdit::findRequested, this, &EditorView::findRequested); - connect (m_targetTextEdit, &TranslationUnitTextEdit::findRequested, this, &EditorView::findRequested); - connect (m_sourceTextEdit, &TranslationUnitTextEdit::findNextRequested, this, &EditorView::findNextRequested); - connect (m_targetTextEdit, &TranslationUnitTextEdit::findNextRequested, this, &EditorView::findNextRequested); - connect (m_sourceTextEdit, &TranslationUnitTextEdit::replaceRequested, this, &EditorView::replaceRequested); - connect (m_targetTextEdit, &TranslationUnitTextEdit::replaceRequested, this, &EditorView::replaceRequested); + connect(m_sourceTextEdit, &TranslationUnitTextEdit::findRequested, this, &EditorView::findRequested); + connect(m_targetTextEdit, &TranslationUnitTextEdit::findRequested, this, &EditorView::findRequested); + connect(m_sourceTextEdit, &TranslationUnitTextEdit::findNextRequested, this, &EditorView::findNextRequested); + connect(m_targetTextEdit, &TranslationUnitTextEdit::findNextRequested, this, &EditorView::findNextRequested); + connect(m_sourceTextEdit, &TranslationUnitTextEdit::replaceRequested, this, &EditorView::replaceRequested); + connect(m_targetTextEdit, &TranslationUnitTextEdit::replaceRequested, this, &EditorView::replaceRequested); - connect (this, &EditorView::doExplicitCompletion, m_targetTextEdit, &TranslationUnitTextEdit::doExplicitCompletion); + connect(this, &EditorView::doExplicitCompletion, m_targetTextEdit, &TranslationUnitTextEdit::doExplicitCompletion); addWidget(m_pluralTabBar); addWidget(m_sourceTextEdit); addWidget(m_targetTextEdit); - QWidget::setTabOrder(m_targetTextEdit,m_sourceTextEdit); - QWidget::setTabOrder(m_sourceTextEdit,m_targetTextEdit); + QWidget::setTabOrder(m_targetTextEdit, m_sourceTextEdit); + QWidget::setTabOrder(m_sourceTextEdit, m_targetTextEdit); setFocusProxy(m_targetTextEdit); // QTimer::singleShot(3000,this,SLOT(setupWhatsThis())); settingsChanged(); @@ -154,7 +154,7 @@ void EditorView::resetFindForCurrent(const DocPosition& pos) { - m_modifiedAfterFind=true; + m_modifiedAfterFind = true; emit signalChanged(pos.entry); } @@ -166,15 +166,14 @@ m_targetTextEdit->document()->setDefaultFont(Settings::msgFont()); #ifndef NOKDE if (m_leds) m_leds->setVisible(Settings::leds()); - else if (Settings::leds()) - { + else if (Settings::leds()) { m_leds = new LedsWidget(this); insertWidget(2, m_leds); - connect (m_targetTextEdit, &TranslationUnitTextEdit::cursorPositionChanged, m_leds, &LedsWidget::cursorPositionChanged); - connect (m_targetTextEdit, &TranslationUnitTextEdit::nonApprovedEntryDisplayed,m_leds->ledFuzzy, &KLed::on); - connect (m_targetTextEdit, &TranslationUnitTextEdit::approvedEntryDisplayed, m_leds->ledFuzzy, &KLed::off); - connect (m_targetTextEdit, &TranslationUnitTextEdit::untranslatedEntryDisplayed,m_leds->ledUntr, &KLed::on); - connect (m_targetTextEdit, &TranslationUnitTextEdit::translatedEntryDisplayed, m_leds->ledUntr, &KLed::off); + connect(m_targetTextEdit, &TranslationUnitTextEdit::cursorPositionChanged, m_leds, &LedsWidget::cursorPositionChanged); + connect(m_targetTextEdit, &TranslationUnitTextEdit::nonApprovedEntryDisplayed, m_leds->ledFuzzy, &KLed::on); + connect(m_targetTextEdit, &TranslationUnitTextEdit::approvedEntryDisplayed, m_leds->ledFuzzy, &KLed::off); + connect(m_targetTextEdit, &TranslationUnitTextEdit::untranslatedEntryDisplayed, m_leds->ledUntr, &KLed::on); + connect(m_targetTextEdit, &TranslationUnitTextEdit::translatedEntryDisplayed, m_leds->ledUntr, &KLed::off); m_targetTextEdit->showPos(m_targetTextEdit->currentPos()); } #endif @@ -191,70 +190,61 @@ { setUpdatesEnabled(false); - bool refresh=(pos.entry==-1); - if (refresh) pos=m_targetTextEdit->currentPos(); + bool refresh = (pos.entry == -1); + if (refresh) pos = m_targetTextEdit->currentPos(); //qCWarning(LOKALIZE_LOG)<<"refresh"<isPlural(pos.entry))) - { - if (Q_UNLIKELY( m_catalog->numberOfPluralForms()!=m_pluralTabBar->count() )) - { - int i=m_pluralTabBar->count(); - if (m_catalog->numberOfPluralForms()>m_pluralTabBar->count()) - while (inumberOfPluralForms()) - m_pluralTabBar->addTab(i18nc("@title:tab","Plural Form %1",++i)); + if (Q_UNLIKELY(m_catalog->isPlural(pos.entry))) { + if (Q_UNLIKELY(m_catalog->numberOfPluralForms() != m_pluralTabBar->count())) { + int i = m_pluralTabBar->count(); + if (m_catalog->numberOfPluralForms() > m_pluralTabBar->count()) + while (i < m_catalog->numberOfPluralForms()) + m_pluralTabBar->addTab(i18nc("@title:tab", "Plural Form %1", ++i)); else - while (i>m_catalog->numberOfPluralForms()) + while (i > m_catalog->numberOfPluralForms()) m_pluralTabBar->removeTab(i--); } m_pluralTabBar->show(); m_pluralTabBar->blockSignals(true); m_pluralTabBar->setCurrentIndex(pos.form); m_pluralTabBar->blockSignals(false); - } - else + } else m_pluralTabBar->hide(); //bool keepCursor=DocPos(pos)==DocPos(_msgidEdit->currentPos()); - bool keepCursor=false; - CatalogString sourceWithTags=m_sourceTextEdit->showPos(pos,CatalogString(),keepCursor); + bool keepCursor = false; + CatalogString sourceWithTags = m_sourceTextEdit->showPos(pos, CatalogString(), keepCursor); //qCWarning(LOKALIZE_LOG)<<"calling showPos"; - QString targetString=m_targetTextEdit->showPos(pos,sourceWithTags,keepCursor).string; + QString targetString = m_targetTextEdit->showPos(pos, sourceWithTags, keepCursor).string; //qCWarning(LOKALIZE_LOG)<<"ss"<<_msgstrEdit->textCursor().anchor()<<_msgstrEdit->textCursor().position(); m_sourceTextEdit->cursorToStart(); m_targetTextEdit->cursorToStart(); - bool untrans=targetString.isEmpty(); + bool untrans = targetString.isEmpty(); //qCWarning(LOKALIZE_LOG)<<"ss1"<<_msgstrEdit->textCursor().anchor()<<_msgstrEdit->textCursor().position(); - if (pos.offset || selection) - { - TranslationUnitTextEdit* msgEdit=(pos.part==DocPosition::Source?m_sourceTextEdit:m_targetTextEdit); - QTextCursor t=msgEdit->textCursor(); - t.movePosition(QTextCursor::NextCharacter,QTextCursor::MoveAnchor,pos.offset); + if (pos.offset || selection) { + TranslationUnitTextEdit* msgEdit = (pos.part == DocPosition::Source ? m_sourceTextEdit : m_targetTextEdit); + QTextCursor t = msgEdit->textCursor(); + t.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, pos.offset); //NOTE this was kinda bug due to on-the-fly msgid wordwrap if (selection) - t.movePosition(QTextCursor::NextCharacter,QTextCursor::KeepAnchor,selection); + t.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, selection); msgEdit->setTextCursor(t); - } - else if (!untrans) - { - QTextCursor t=m_targetTextEdit->textCursor(); + } else if (!untrans) { + QTextCursor t = m_targetTextEdit->textCursor(); //what if msg starts with a tag? - if (Q_UNLIKELY( targetString.startsWith('<') )) - { - int offset=targetString.indexOf(QRegExp(QStringLiteral(">[^<]"))); - if ( offset!=-1 ) - t.movePosition(QTextCursor::NextCharacter,QTextCursor::MoveAnchor,offset+1); - } - else if (Q_UNLIKELY( targetString.startsWith(TAGRANGE_IMAGE_SYMBOL) )) - { - int offset=targetString.indexOf(QRegExp(QStringLiteral("[^")%QChar(TAGRANGE_IMAGE_SYMBOL)%']')); - if ( offset!=-1 ) - t.movePosition(QTextCursor::NextCharacter,QTextCursor::MoveAnchor,offset+1); + if (Q_UNLIKELY(targetString.startsWith('<'))) { + int offset = targetString.indexOf(QRegExp(QStringLiteral(">[^<]"))); + if (offset != -1) + t.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, offset + 1); + } else if (Q_UNLIKELY(targetString.startsWith(TAGRANGE_IMAGE_SYMBOL))) { + int offset = targetString.indexOf(QRegExp(QStringLiteral("[^") % QChar(TAGRANGE_IMAGE_SYMBOL) % ']')); + if (offset != -1) + t.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, offset + 1); } m_targetTextEdit->setTextCursor(t); } @@ -273,27 +263,26 @@ void EditorView::unwrap(TranslationUnitTextEdit* editor) { if (!editor) - editor=m_targetTextEdit; + editor = m_targetTextEdit; - QTextCursor t=editor->document()->find(QRegExp("[^(\\\\n)]$")); + QTextCursor t = editor->document()->find(QRegExp("[^(\\\\n)]$")); if (t.isNull()) return; - if (editor==m_targetTextEdit) - m_catalog->beginMacro(i18nc("@item Undo action item","Unwrap")); + if (editor == m_targetTextEdit) + m_catalog->beginMacro(i18nc("@item Undo action item", "Unwrap")); t.movePosition(QTextCursor::EndOfLine); if (!t.atEnd()) t.deleteChar(); QRegExp rx("[^(\\\\n)>]$"); //remove '\n's skipping "\\\\n" - while (!(t=editor->document()->find(rx,t)).isNull()) - { + while (!(t = editor->document()->find(rx, t)).isNull()) { t.movePosition(QTextCursor::EndOfLine); if (!t.atEnd()) t.deleteChar(); } - if (editor==m_targetTextEdit) + if (editor == m_targetTextEdit) m_catalog->endMacro(); } @@ -333,30 +322,30 @@ void EditorView::toggleBookmark(bool checked) { - if (Q_UNLIKELY( m_targetTextEdit->currentPos().entry==-1 )) + if (Q_UNLIKELY(m_targetTextEdit->currentPos().entry == -1)) return; - m_catalog->setBookmark(m_targetTextEdit->currentPos().entry,checked); + m_catalog->setBookmark(m_targetTextEdit->currentPos().entry, checked); } void EditorView::toggleApprovement() { //qCWarning(LOKALIZE_LOG)<<"called"; - if (Q_UNLIKELY( m_targetTextEdit->currentPos().entry==-1 )) + if (Q_UNLIKELY(m_targetTextEdit->currentPos().entry == -1)) return; - bool newState=!m_catalog->isApproved(m_targetTextEdit->currentPos().entry); - SetStateCmd::push(m_catalog,m_targetTextEdit->currentPos(),newState); + bool newState = !m_catalog->isApproved(m_targetTextEdit->currentPos().entry); + SetStateCmd::push(m_catalog, m_targetTextEdit->currentPos(), newState); emit signalApprovedEntryDisplayed(newState); } void EditorView::setState(TargetState state) { - if (Q_UNLIKELY( m_targetTextEdit->currentPos().entry==-1 - || m_catalog->state(m_targetTextEdit->currentPos())==state)) + if (Q_UNLIKELY(m_targetTextEdit->currentPos().entry == -1 + || m_catalog->state(m_targetTextEdit->currentPos()) == state)) return; - SetStateCmd::instantiateAndPush(m_catalog,m_targetTextEdit->currentPos(),state); + SetStateCmd::instantiateAndPush(m_catalog, m_targetTextEdit->currentPos(), state); emit signalApprovedEntryDisplayed(m_catalog->isApproved(m_targetTextEdit->currentPos())); } diff --git a/src/filesearch/filesearchtab.h b/src/filesearch/filesearchtab.h --- a/src/filesearch/filesearchtab.h +++ b/src/filesearch/filesearchtab.h @@ -63,12 +63,18 @@ FileSearchTab(QWidget *parent); ~FileSearchTab(); - void hideDocks(){}; - void showDocks(){}; + void hideDocks() {}; + void showDocks() {}; #ifndef NOKDE - KXMLGUIClient* guiClient(){return (KXMLGUIClient*)this;} + KXMLGUIClient* guiClient() + { + return (KXMLGUIClient*)this; + } QString dbusObjectPath(); - int dbusId(){return m_dbusId;} + int dbusId() + { + return m_dbusId; + } #endif public slots: @@ -80,7 +86,10 @@ Q_SCRIPTABLE void setSourceQuery(const QString&); Q_SCRIPTABLE void setTargetQuery(const QString&); #ifndef NOKDE - Q_SCRIPTABLE bool findGuiText(QString text){return findGuiTextPackage(text,QString());} + Q_SCRIPTABLE bool findGuiText(QString text) + { + return findGuiTextPackage(text, QString()); + } Q_SCRIPTABLE bool findGuiTextPackage(QString text, QString package); #endif void fileSearchNext(); @@ -111,15 +120,14 @@ QVector m_runningJobs; - //to avoid results from previous search showing up in the new one + //to avoid results from previous search showing up in the new one int m_lastSearchNumber; int m_dbusId; static QList ids; }; -struct FileSearchResult -{ +struct FileSearchResult { DocPos docPos; QString source; @@ -139,12 +147,11 @@ typedef QMap > FileSearchResults; -struct SearchResult: public FileSearchResult -{ +struct SearchResult: public FileSearchResult { QString filepath; - SearchResult(const FileSearchResult& fsr):FileSearchResult(fsr){} - SearchResult(){} + SearchResult(const FileSearchResult& fsr): FileSearchResult(fsr) {} + SearchResult() {} }; typedef QVector SearchResults; @@ -154,34 +161,44 @@ Q_OBJECT public: - enum FileSearchModelColumns - { - Source=0, + enum FileSearchModelColumns { + Source = 0, Target, //Context, Filepath, TranslationStatus, //Notes, ColumnCount }; - enum Roles - { - FullPathRole=Qt::UserRole, - TransStateRole=Qt::UserRole+1, - HtmlDisplayRole=Qt::UserRole+2 + enum Roles { + FullPathRole = Qt::UserRole, + TransStateRole = Qt::UserRole + 1, + HtmlDisplayRole = Qt::UserRole + 2 }; FileSearchModel(QObject* parent); - ~FileSearchModel(){} + ~FileSearchModel() {} QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - QVariant data(const QModelIndex& item, int role=Qt::DisplayRole) const; - int columnCount(const QModelIndex& parent=QModelIndex()) const {Q_UNUSED(parent) return ColumnCount;} - int rowCount(const QModelIndex& parent = QModelIndex()) const {Q_UNUSED(parent) return m_searchResults.size();} + QVariant data(const QModelIndex& item, int role = Qt::DisplayRole) const; + int columnCount(const QModelIndex& parent = QModelIndex()) const + { + Q_UNUSED(parent) return ColumnCount; + } + int rowCount(const QModelIndex& parent = QModelIndex()) const + { + Q_UNUSED(parent) return m_searchResults.size(); + } - SearchResults searchResults()const {return m_searchResults;} - SearchResult searchResult(const QModelIndex& item) const {return m_searchResults.at(item.row());} + SearchResults searchResults()const + { + return m_searchResults; + } + SearchResult searchResult(const QModelIndex& item) const + { + return m_searchResults.at(item.row()); + } void appendSearchResults(const SearchResults&); void clear(); @@ -200,14 +217,14 @@ public: SearchFileListView(QWidget*); - ~SearchFileListView(){} + ~SearchFileListView() {} void addFiles(const QStringList& files); void addFilesFast(const QStringList& files); QStringList files()const; - void scrollTo(const QString& file=QString()); + void scrollTo(const QString& file = QString()); public slots: void clear(); @@ -246,8 +263,7 @@ Ui_MassReplaceOptions* ui; }; -struct SearchParams -{ +struct SearchParams { QRegExp sourcePattern; QRegExp targetPattern; QRegExp notesPattern; @@ -259,25 +275,28 @@ bool isEmpty() const; - SearchParams():invertSource(false), invertTarget(false){memset(states, 0, sizeof(states));} + SearchParams(): invertSource(false), invertTarget(false) + { + memset(states, 0, sizeof(states)); + } }; #include class SearchJob: public QObject, public QRunnable { Q_OBJECT public: - explicit SearchJob(const QStringList& f, + explicit SearchJob(const QStringList& f, const SearchParams& sp, const QVector& r, int sn, - QObject* parent=0); - ~SearchJob(){} + QObject* parent = 0); + ~SearchJob() {} signals: void done(SearchJob*); protected: - void run (); + void run(); public: QStringList files; SearchParams searchParams; @@ -299,8 +318,8 @@ const QRegExp& s, const QString& r, //int sn, - QObject* parent=0); - ~MassReplaceJob(){} + QObject* parent = 0); + ~MassReplaceJob() {} signals: void done(MassReplaceJob*); diff --git a/src/filesearch/filesearchtab.cpp b/src/filesearch/filesearchtab.cpp --- a/src/filesearch/filesearchtab.cpp +++ b/src/filesearch/filesearchtab.cpp @@ -69,28 +69,31 @@ class FileListModel: public QStringListModel { public: - FileListModel(QObject* parent): QStringListModel(parent){} - QVariant data(const QModelIndex& item, int role=Qt::DisplayRole) const; - Qt::ItemFlags flags(const QModelIndex&) const {return Qt::ItemIsEnabled|Qt::ItemIsSelectable;} + FileListModel(QObject* parent): QStringListModel(parent) {} + QVariant data(const QModelIndex& item, int role = Qt::DisplayRole) const; + Qt::ItemFlags flags(const QModelIndex&) const + { + return Qt::ItemIsEnabled | Qt::ItemIsSelectable; + } }; QVariant FileListModel::data(const QModelIndex& item, int role) const { - if (role==Qt::DisplayRole) + if (role == Qt::DisplayRole) return shorterFilePath(stringList().at(item.row())); - if (role==Qt::UserRole) + if (role == Qt::UserRole) return stringList().at(item.row()); return QVariant(); } SearchFileListView::SearchFileListView(QWidget* parent) - : QDockWidget( i18nc("@title:window","File List"), parent) - , m_browser(new QTreeView(this)) - , m_background(new QLabel(i18n("Drop translation files here..."), this)) - , m_model(new FileListModel(this)) + : QDockWidget(i18nc("@title:window", "File List"), parent) + , m_browser(new QTreeView(this)) + , m_background(new QLabel(i18n("Drop translation files here..."), this)) + , m_model(new FileListModel(this)) { setWidget(m_background); - m_background->setMinimumWidth(QFontMetrics(font()).averageCharWidth()*30); + m_background->setMinimumWidth(QFontMetrics(font()).averageCharWidth() * 30); m_background->setAlignment(Qt::AlignCenter); m_browser->hide(); m_browser->setModel(m_model); @@ -102,10 +105,10 @@ m_browser->setContextMenuPolicy(Qt::ActionsContextMenu); - QAction* action=new QAction(i18nc("@action:inmenu", "Clear"), m_browser); + QAction* action = new QAction(i18nc("@action:inmenu", "Clear"), m_browser); connect(action, &QAction::triggered, this, &SearchFileListView::clear); m_browser->addAction(action); - + connect(m_browser, &QTreeView::activated, this, &SearchFileListView::requestFileOpen); } @@ -126,18 +129,18 @@ //ensure unquiness, sorting the list along the way QMap map; - foreach(const QString& filepath, m_model->stringList()) - map[filepath]=true; - foreach(const QString& filepath, files) - map[filepath]=true; + foreach (const QString& filepath, m_model->stringList()) + map[filepath] = true; + foreach (const QString& filepath, files) + map[filepath] = true; m_model->setStringList(map.keys()); } void SearchFileListView::addFilesFast(const QStringList& files) { if (files.size()) - m_model->setStringList(m_model->stringList()+files); + m_model->setStringList(m_model->stringList() + files); } void SearchFileListView::clear() @@ -153,13 +156,12 @@ void SearchFileListView::scrollTo(const QString& file) { - if (file.isEmpty()) - { + if (file.isEmpty()) { m_browser->scrollToTop(); return; } - int idx=m_model->stringList().indexOf(file); - if (idx!=-1) + int idx = m_model->stringList().indexOf(file); + if (idx != -1) m_browser->scrollTo(m_model->index(idx, 0), QAbstractItemView::PositionAtCenter); } @@ -182,147 +184,135 @@ bool SearchParams::isEmpty() const { return sourcePattern.pattern().isEmpty() - && targetPattern.pattern().isEmpty(); + && targetPattern.pattern().isEmpty(); } SearchJob::SearchJob(const QStringList& f, const SearchParams& sp, const QVector& r, int sn, QObject*) - : QRunnable() - , files(f) - , searchParams(sp) - , rules(r) - , searchNumber(sn) - , m_size(0) + : QRunnable() + , files(f) + , searchParams(sp) + , rules(r) + , searchNumber(sn) + , m_size(0) { setAutoDelete(false); } void SearchJob::run() { - QTime a;a.start(); - bool removeAmpFromSource = searchParams.sourcePattern.patternSyntax()==QRegExp::FixedString - && !searchParams.sourcePattern.pattern().contains(QLatin1Char('&')); - bool removeAmpFromTarget = searchParams.targetPattern.patternSyntax()==QRegExp::FixedString - && !searchParams.targetPattern.pattern().contains(QLatin1Char('&')); - foreach(const QString& filePath, files) - { - Catalog catalog(0); - if (Q_UNLIKELY(catalog.loadFromUrl(filePath, QString(), &m_size, true)!=0)) + QTime a; a.start(); + bool removeAmpFromSource = searchParams.sourcePattern.patternSyntax() == QRegExp::FixedString + && !searchParams.sourcePattern.pattern().contains(QLatin1Char('&')); + bool removeAmpFromTarget = searchParams.targetPattern.patternSyntax() == QRegExp::FixedString + && !searchParams.targetPattern.pattern().contains(QLatin1Char('&')); + foreach (const QString& filePath, files) { + Catalog catalog(0); + if (Q_UNLIKELY(catalog.loadFromUrl(filePath, QString(), &m_size, true) != 0)) continue; //QVector catalogResults; - int numberOfEntries=catalog.numberOfEntries(); + int numberOfEntries = catalog.numberOfEntries(); DocPosition pos(0); - for (;pos.entry positions(2); - int matchedQaRule=findMatchingRule(rules, r.source, r.target, positions); - if (matchedQaRule==-1) + int matchedQaRule = findMatchingRule(rules, r.source, r.target, positions); + if (matchedQaRule == -1) continue; if (positions.at(0).len) - r.sourcePositions< map; - for (int i=0;is.string.length() || replaceWhat.pattern().startsWith('^')) + if (pos > s.string.length() || replaceWhat.pattern().startsWith('^')) break; - pos=replaceWhat.indexIn(s.string, pos); + pos = replaceWhat.indexIn(s.string, pos); } } @@ -339,23 +329,22 @@ QVariant FileSearchModel::headerData(int section, Qt::Orientation, int role) const { - if (role!=Qt::DisplayRole) + if (role != Qt::DisplayRole) return QVariant(); - switch (section) - { - case FileSearchModel::Source: return i18nc("@title:column Original text","Source"); - case FileSearchModel::Target: return i18nc("@title:column Text in target language","Target"); - //case FileSearchModel::Context: return i18nc("@title:column","Context"); - case FileSearchModel::Filepath: return i18nc("@title:column","File"); - case FileSearchModel::TranslationStatus: return i18nc("@title:column","Translation Status"); + switch (section) { + case FileSearchModel::Source: return i18nc("@title:column Original text", "Source"); + case FileSearchModel::Target: return i18nc("@title:column Text in target language", "Target"); + //case FileSearchModel::Context: return i18nc("@title:column","Context"); + case FileSearchModel::Filepath: return i18nc("@title:column", "File"); + case FileSearchModel::TranslationStatus: return i18nc("@title:column", "Translation Status"); } return QVariant(); } void FileSearchModel::appendSearchResults(const SearchResults& results) { - beginInsertRows(QModelIndex(), m_searchResults.size(), m_searchResults.size()+results.size()-1); - m_searchResults+=results; + beginInsertRows(QModelIndex(), m_searchResults.size(), m_searchResults.size() + results.size() - 1); + m_searchResults += results; endInsertRows(); } @@ -368,50 +357,46 @@ QVariant FileSearchModel::data(const QModelIndex& item, int role) const { - bool doHtml=(role==FastSizeHintItemDelegate::HtmlDisplayRole); + bool doHtml = (role == FastSizeHintItemDelegate::HtmlDisplayRole); if (doHtml) - role=Qt::DisplayRole; + role = Qt::DisplayRole; - if (role==Qt::DisplayRole) - { + if (role == Qt::DisplayRole) { QString result; - const SearchResult& sr=m_searchResults.at(item.row()); - if (item.column()==Source) - result=sr.source; - if (item.column()==Target) - result=sr.target; - if (item.column()==Filepath) - result=shorterFilePath(sr.filepath); - - if (doHtml && item.column()<=FileSearchModel::Target) - { + const SearchResult& sr = m_searchResults.at(item.row()); + if (item.column() == Source) + result = sr.source; + if (item.column() == Target) + result = sr.target; + if (item.column() == Filepath) + result = shorterFilePath(sr.filepath); + + if (doHtml && item.column() <= FileSearchModel::Target) { if (result.isEmpty()) return result; const QString startBld = QStringLiteral("_ST_"); const QString endBld = QStringLiteral("_END_"); const QString startBldTag = QStringLiteral(""); const QString endBldTag = QStringLiteral(""); - if (item.column()==FileSearchModel::Target && !m_replaceWhat.isEmpty()) - { + if (item.column() == FileSearchModel::Target && !m_replaceWhat.isEmpty()) { result.replace(m_replaceWhat, m_replaceWith); - QString escaped=convertToHtml(result, !sr.isApproved); + QString escaped = convertToHtml(result, !sr.isApproved); escaped.replace(startBld, startBldTag); escaped.replace(endBld, endBldTag); return escaped; } - const QVector& occurences=item.column()==FileSearchModel::Source?sr.sourcePositions:sr.targetPositions; - int occ=occurences.count(); - while (--occ>=0) - { - const StartLen& sl=occurences.at(occ); - result.insert(sl.start+sl.len, endBld); + const QVector& occurences = item.column() == FileSearchModel::Source ? sr.sourcePositions : sr.targetPositions; + int occ = occurences.count(); + while (--occ >= 0) { + const StartLen& sl = occurences.at(occ); + result.insert(sl.start + sl.len, endBld); result.insert(sl.start, startBld); } - /* !isApproved(sr.state, Project::instance()->local()->role())*/ - QString escaped=convertToHtml(result, item.column()==FileSearchModel::Target && !sr.isApproved); + /* !isApproved(sr.state, Project::instance()->local()->role())*/ + QString escaped = convertToHtml(result, item.column() == FileSearchModel::Target && !sr.isApproved); escaped.replace(startBld, startBldTag); escaped.replace(endBld, endBldTag); @@ -421,22 +406,21 @@ } - if (role==Qt::UserRole) - { - const SearchResult& sr=m_searchResults.at(item.row()); - if (item.column()==Filepath) + if (role == Qt::UserRole) { + const SearchResult& sr = m_searchResults.at(item.row()); + if (item.column() == Filepath) return sr.filepath; } return QVariant(); } void FileSearchModel::setReplacePreview(const QRegExp& s, const QString& r) { - m_replaceWhat=s; - m_replaceWith=QLatin1String("_ST_") % r % QLatin1String("_END_"); - - emit dataChanged(index(0, Target), index(rowCount()-1, Target)); + m_replaceWhat = s; + m_replaceWith = QLatin1String("_ST_") % r % QLatin1String("_END_"); + + emit dataChanged(index(0, Target), index(rowCount() - 1, Target)); } @@ -450,53 +434,53 @@ , m_lastSearchNumber(0) , m_dbusId(-1) { - setWindowTitle(i18nc("@title:window","Search and replace in files")); + setWindowTitle(i18nc("@title:window", "Search and replace in files")); setAcceptDrops(true); - QWidget* w=new QWidget(this); - ui_fileSearchOptions=new Ui_FileSearchOptions; + QWidget* w = new QWidget(this); + ui_fileSearchOptions = new Ui_FileSearchOptions; ui_fileSearchOptions->setupUi(w); setCentralWidget(w); - QShortcut* sh=new QShortcut(Qt::CTRL+Qt::Key_L, this); + QShortcut* sh = new QShortcut(Qt::CTRL + Qt::Key_L, this); connect(sh, &QShortcut::activated, ui_fileSearchOptions->querySource, QOverload<>::of(&QLineEdit::setFocus)); setFocusProxy(ui_fileSearchOptions->querySource); - sh=new QShortcut(Qt::Key_Escape,this,SLOT(stopSearch()),0,Qt::WidgetWithChildrenShortcut); + sh = new QShortcut(Qt::Key_Escape, this, SLOT(stopSearch()), 0, Qt::WidgetWithChildrenShortcut); - QTreeView* view=ui_fileSearchOptions->treeView; + QTreeView* view = ui_fileSearchOptions->treeView; QVector singleLineColumns(FileSearchModel::ColumnCount, false); - singleLineColumns[FileSearchModel::Filepath]=true; - singleLineColumns[FileSearchModel::TranslationStatus]=true; + singleLineColumns[FileSearchModel::Filepath] = true; + singleLineColumns[FileSearchModel::TranslationStatus] = true; //singleLineColumns[TMDBModel::Context]=true; QVector richTextColumns(FileSearchModel::ColumnCount, false); - richTextColumns[FileSearchModel::Source]=true; - richTextColumns[FileSearchModel::Target]=true; - view->setItemDelegate(new FastSizeHintItemDelegate(this,singleLineColumns,richTextColumns)); + richTextColumns[FileSearchModel::Source] = true; + richTextColumns[FileSearchModel::Target] = true; + view->setItemDelegate(new FastSizeHintItemDelegate(this, singleLineColumns, richTextColumns)); connect(m_model, &FileSearchModel::modelReset, (FastSizeHintItemDelegate*)view->itemDelegate(), &FastSizeHintItemDelegate::reset); connect(m_model, &FileSearchModel::dataChanged, (FastSizeHintItemDelegate*)view->itemDelegate(), &FastSizeHintItemDelegate::reset); //connect(m_model,SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)),view->itemDelegate(),SLOT(reset())); //connect(m_proxyModel,SIGNAL(layoutChanged()),view->itemDelegate(),SLOT(reset())); //connect(m_proxyModel,SIGNAL(layoutChanged()),this,SLOT(displayTotalResultCount())); view->setContextMenuPolicy(Qt::ActionsContextMenu); - QAction* a=new QAction(i18n("Copy source to clipboard"),view); + QAction* a = new QAction(i18n("Copy source to clipboard"), view); a->setShortcut(Qt::CTRL + Qt::Key_S); a->setShortcutContext(Qt::WidgetWithChildrenShortcut); connect(a, &QAction::triggered, this, &FileSearchTab::copySourceToClipboard); view->addAction(a); - a=new QAction(i18n("Copy target to clipboard"),view); + a = new QAction(i18n("Copy target to clipboard"), view); a->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return)); a->setShortcutContext(Qt::WidgetWithChildrenShortcut); connect(a, &QAction::triggered, this, &FileSearchTab::copyTargetToClipboard); view->addAction(a); - a=new QAction(i18n("Open file"),view); + a = new QAction(i18n("Open file"), view); a->setShortcut(QKeySequence(Qt::Key_Return)); a->setShortcutContext(Qt::WidgetWithChildrenShortcut); connect(a, &QAction::triggered, this, &FileSearchTab::openFile); @@ -521,41 +505,41 @@ //BEGIN resizeColumnToContents - static const int maxInitialWidths[]={QApplication::desktop()->availableGeometry().width()/3,QApplication::desktop()->availableGeometry().width()/3}; - int column=sizeof(maxInitialWidths)/sizeof(int); - while (--column>=0) + static const int maxInitialWidths[] = {QApplication::desktop()->availableGeometry().width() / 3, QApplication::desktop()->availableGeometry().width() / 3}; + int column = sizeof(maxInitialWidths) / sizeof(int); + while (--column >= 0) view->setColumnWidth(column, maxInitialWidths[column]); //END resizeColumnToContents - int i=6; - while (--i>ID_STATUS_PROGRESS) - statusBarItems.insert(i,QString()); + int i = 6; + while (--i > ID_STATUS_PROGRESS) + statusBarItems.insert(i, QString()); #ifndef NOKDE - setXMLFile(QStringLiteral("filesearchtabui.rc"),true); + setXMLFile(QStringLiteral("filesearchtabui.rc"), true); dbusObjectPath(); #endif - KActionCollection* ac=actionCollection(); - KActionCategory* srf=new KActionCategory(i18nc("@title actions category","Search and replace in files"), ac); + KActionCollection* ac = actionCollection(); + KActionCategory* srf = new KActionCategory(i18nc("@title actions category", "Search and replace in files"), ac); m_searchFileListView = new SearchFileListView(this); //m_searchFileListView->hide(); addDockWidget(Qt::RightDockWidgetArea, m_searchFileListView); - srf->addAction( QStringLiteral("showfilelist_action"), m_searchFileListView->toggleViewAction() ); + srf->addAction(QStringLiteral("showfilelist_action"), m_searchFileListView->toggleViewAction()); connect(m_searchFileListView, &SearchFileListView::fileOpenRequested, this, QOverload::of(&FileSearchTab::fileOpenRequested)); m_massReplaceView = new MassReplaceView(this); addDockWidget(Qt::RightDockWidgetArea, m_massReplaceView); - srf->addAction( QStringLiteral("showmassreplace_action"), m_massReplaceView->toggleViewAction() ); + srf->addAction(QStringLiteral("showmassreplace_action"), m_massReplaceView->toggleViewAction()); connect(m_massReplaceView, &MassReplaceView::previewRequested, m_model, &FileSearchModel::setReplacePreview); connect(m_massReplaceView, &MassReplaceView::replaceRequested, this, &FileSearchTab::massReplace); //m_massReplaceView->hide(); m_qaView = new QaView(this); m_qaView->hide(); addDockWidget(Qt::RightDockWidgetArea, m_qaView); - srf->addAction( QStringLiteral("showqa_action"), m_qaView->toggleViewAction() ); + srf->addAction(QStringLiteral("showqa_action"), m_qaView->toggleViewAction()); connect(m_qaView, &QaView::rulesChanged, this, &FileSearchTab::performSearch); connect(m_qaView->toggleViewAction(), &QAction::toggled, this, &FileSearchTab::performSearch, Qt::QueuedConnection); @@ -576,55 +560,52 @@ void FileSearchTab::performSearch() { - if (m_searchFileListView->files().isEmpty()) - { + if (m_searchFileListView->files().isEmpty()) { addFilesToSearch(doScanRecursive(QDir(Project::instance()->poDir()))); if (m_searchFileListView->files().isEmpty()) return; } m_model->clear(); - statusBarItems.insert(1,QString()); + statusBarItems.insert(1, QString()); m_searchFileListView->scrollTo(); m_lastSearchNumber++; SearchParams sp; sp.sourcePattern.setPattern(ui_fileSearchOptions->querySource->text()); sp.targetPattern.setPattern(ui_fileSearchOptions->queryTarget->text()); - sp.invertSource=ui_fileSearchOptions->invertSource->isChecked(); - sp.invertTarget=ui_fileSearchOptions->invertTarget->isChecked(); + sp.invertSource = ui_fileSearchOptions->invertSource->isChecked(); + sp.invertTarget = ui_fileSearchOptions->invertTarget->isChecked(); - QVector rules=m_qaView->isVisible()?m_qaView->rules():QVector(); + QVector rules = m_qaView->isVisible() ? m_qaView->rules() : QVector(); if (sp.isEmpty() && rules.isEmpty()) return; - if (!ui_fileSearchOptions->regEx->isChecked()) - { + if (!ui_fileSearchOptions->regEx->isChecked()) { sp.sourcePattern.setPatternSyntax(QRegExp::FixedString); sp.targetPattern.setPatternSyntax(QRegExp::FixedString); } -/* - else - { - sp.sourcePattern.setMinimal(true); - sp.targetPattern.setMinimal(true); - } -*/ + /* + else + { + sp.sourcePattern.setMinimal(true); + sp.targetPattern.setMinimal(true); + } + */ stopSearch(); m_massReplaceView->deactivatePreview(); - QStringList files=m_searchFileListView->files(); - for(int i=0; ifiles(); + for (int i = 0; i < files.size(); i += 100) { QStringList batch; - int lim=qMin(files.size(), i+100); - for(int j=i; jstart(job); m_runningJobs.append(job); @@ -634,8 +615,8 @@ void FileSearchTab::stopSearch() { #if QT_VERSION >= 0x050500 - int i=m_runningJobs.size(); - while (--i>=0) + int i = m_runningJobs.size(); + while (--i >= 0) QThreadPool::globalInstance()->cancel(m_runningJobs.at(i)); #endif m_runningJobs.clear(); @@ -646,16 +627,15 @@ { #define BATCH_SIZE 20 - SearchResults searchResults=m_model->searchResults(); + SearchResults searchResults = m_model->searchResults(); - for (int i=0;istart(job); m_runningJobs.append(job); @@ -665,7 +645,7 @@ static void copy(QTreeView* view, int column) { - QApplication::clipboard()->setText( view->currentIndex().sibling(view->currentIndex().row(),column).data().toString()); + QApplication::clipboard()->setText(view->currentIndex().sibling(view->currentIndex().row(), column).data().toString()); } void FileSearchTab::copySourceToClipboard() @@ -680,26 +660,25 @@ void FileSearchTab::openFile() { - QModelIndex item=ui_fileSearchOptions->treeView->currentIndex(); - SearchResult sr=m_model->searchResult(item); - DocPosition docPos=sr.docPos.toDocPosition(); - int selection=0; - if (sr.targetPositions.size()) - { - docPos.offset=sr.targetPositions.first().start; - selection =sr.targetPositions.first().len; + QModelIndex item = ui_fileSearchOptions->treeView->currentIndex(); + SearchResult sr = m_model->searchResult(item); + DocPosition docPos = sr.docPos.toDocPosition(); + int selection = 0; + if (sr.targetPositions.size()) { + docPos.offset = sr.targetPositions.first().start; + selection = sr.targetPositions.first().len; } - qCDebug(LOKALIZE_LOG)<<"fileOpenRequest"<treeView->currentIndex(); - int row=item.row(); - int rowCount=m_model->rowCount(); - - if (++row>=rowCount) //ok if row was -1 (no solection) + QModelIndex item = ui_fileSearchOptions->treeView->currentIndex(); + int row = item.row(); + int rowCount = m_model->rowCount(); + + if (++row >= rowCount) //ok if row was -1 (no solection) return; ui_fileSearchOptions->treeView->setCurrentIndex(item.sibling(row, item.column())); @@ -711,16 +690,15 @@ { QStringList result; - int i=urls.size(); - while(--i>=0) - { - if (urls.at(i).isEmpty() || urls.at(i).path().isEmpty() ) //NOTE is this a Qt bug? + int i = urls.size(); + while (--i >= 0) { + if (urls.at(i).isEmpty() || urls.at(i).path().isEmpty()) //NOTE is this a Qt bug? continue; - QString path=urls.at(i).toLocalFile(); + QString path = urls.at(i).toLocalFile(); if (Catalog::extIsSupported(path)) result.append(path); else - result+=doScanRecursive(QDir(path)); + result += doScanRecursive(QDir(path)); } return result; @@ -730,28 +708,28 @@ static QStringList doScanRecursive(const QDir& dir) { QStringList result; - QStringList subDirs(dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot|QDir::Readable)); - int i=subDirs.size(); - while(--i>=0) - result+=doScanRecursive(QDir(dir.filePath(subDirs.at(i)))); - - QStringList filters=Catalog::supportedExtensions(); - i=filters.size(); - while(--i>=0) + QStringList subDirs(dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Readable)); + int i = subDirs.size(); + while (--i >= 0) + result += doScanRecursive(QDir(dir.filePath(subDirs.at(i)))); + + QStringList filters = Catalog::supportedExtensions(); + i = filters.size(); + while (--i >= 0) filters[i].prepend('*'); - QStringList files(dir.entryList(filters,QDir::Files|QDir::NoDotAndDotDot|QDir::Readable)); - i=files.size(); + QStringList files(dir.entryList(filters, QDir::Files | QDir::NoDotAndDotDot | QDir::Readable)); + i = files.size(); - while(--i>=0) + while (--i >= 0) result.append(dir.filePath(files.at(i))); return result; } void FileSearchTab::dragEnterEvent(QDragEnterEvent* event) { - if(dragIsAcceptable(event->mimeData()->urls())) + if (dragIsAcceptable(event->mimeData()->urls())) event->acceptProposedAction(); } @@ -782,40 +760,39 @@ { j->deleteLater(); - if (j->searchNumber!=m_lastSearchNumber) + if (j->searchNumber != m_lastSearchNumber) return; -/* - SearchResults searchResults; - - FileSearchResults::const_iterator i = j->results.constBegin(); - while (i != j->results.constEnd()) - { - foreach(const FileSearchResult& fsr, i.value()) + /* + SearchResults searchResults; + + FileSearchResults::const_iterator i = j->results.constBegin(); + while (i != j->results.constEnd()) { - SearchResult sr(fsr); - sr.filepath=i.key(); - searchResults<appendSearchResults(searchResults); -*/ - if (j->results.size()) - { + m_model->appendSearchResults(searchResults); + */ + if (j->results.size()) { m_model->appendSearchResults(j->results); m_searchFileListView->scrollTo(j->results.last().filepath); } - statusBarItems.insert(1,i18nc("@info:status message entries","Total: %1", m_model->rowCount())); + statusBarItems.insert(1, i18nc("@info:status message entries", "Total: %1", m_model->rowCount())); //ui_fileSearchOptions->treeView->setFocus(); } void FileSearchTab::replaceJobDone(MassReplaceJob* j) { j->deleteLater(); - ui_fileSearchOptions->treeView->scrollTo(m_model->index(j->globalPos+j->searchResults.count(), 0)); + ui_fileSearchOptions->treeView->scrollTo(m_model->index(j->globalPos + j->searchResults.count(), 0)); } @@ -825,35 +802,35 @@ //BEGIN MASS REPLACE MassReplaceView::MassReplaceView(QWidget* parent) - : QDockWidget(i18nc("@title:window","Mass replace"), parent) + : QDockWidget(i18nc("@title:window", "Mass replace"), parent) , ui(new Ui_MassReplaceOptions) { - QWidget* base=new QWidget(this); + QWidget* base = new QWidget(this); setWidget(base); ui->setupUi(base); connect(ui->doPreview, &QPushButton::toggled, this, &MassReplaceView::requestPreview); connect(ui->doReplace, &QPushButton::clicked, this, &MassReplaceView::requestReplace); -/* - QLabel* rl=new QLabel(i18n("Replace:"), base); - QLineEdit* searchEdit=new QLineEdit(base); - QHBoxLayout* searchL=new QHBoxLayout(); - searchL->addWidget(rl); - searchL->addWidget(searchEdit); - - QLabel* wl=new QLabel(i18n("With:"), base); - wl->setAlignment(Qt::AlignRight); - wl->setMinimumSize(rl->minimumSizeHint()); - QLineEdit* replacementEdit=new QLineEdit(base); - QHBoxLayout* replacementL=new QHBoxLayout(); - replacementL->addWidget(wl); - replacementL->addWidget(replacementEdit); - - FlowLayout* fl=new FlowLayout(); - fl->addItem(searchL); - fl->addItem(replacementL); - base->setLayout(fl); - */ + /* + QLabel* rl=new QLabel(i18n("Replace:"), base); + QLineEdit* searchEdit=new QLineEdit(base); + QHBoxLayout* searchL=new QHBoxLayout(); + searchL->addWidget(rl); + searchL->addWidget(searchEdit); + + QLabel* wl=new QLabel(i18n("With:"), base); + wl->setAlignment(Qt::AlignRight); + wl->setMinimumSize(rl->minimumSizeHint()); + QLineEdit* replacementEdit=new QLineEdit(base); + QHBoxLayout* replacementL=new QHBoxLayout(); + replacementL->addWidget(wl); + replacementL->addWidget(replacementEdit); + + FlowLayout* fl=new FlowLayout(); + fl->addItem(searchL); + fl->addItem(replacementL); + base->setLayout(fl); + */ } MassReplaceView::~MassReplaceView() @@ -863,14 +840,14 @@ static QRegExp regExpFromUi(const QString& s, Ui_MassReplaceOptions* ui) { - return QRegExp(s, ui->matchCase->isChecked()?Qt::CaseSensitive:Qt::CaseInsensitive, - ui->useRegExps->isChecked()?QRegExp::FixedString:QRegExp::RegExp); + return QRegExp(s, ui->matchCase->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive, + ui->useRegExps->isChecked() ? QRegExp::FixedString : QRegExp::RegExp); } void MassReplaceView::requestPreviewUpdate() { - QString s=ui->searchText->text(); - QString r=ui->replaceText->text(); + QString s = ui->searchText->text(); + QString r = ui->replaceText->text(); if (s.length()) ui->doReplace->setEnabled(true); @@ -881,17 +858,14 @@ void MassReplaceView::requestPreview(bool enable) { - if (enable) - { + if (enable) { connect(ui->searchText, &QLineEdit::textEdited, this, &MassReplaceView::requestPreviewUpdate); connect(ui->replaceText, &QLineEdit::textEdited, this, &MassReplaceView::requestPreviewUpdate); connect(ui->useRegExps, &QCheckBox::toggled, this, &MassReplaceView::requestPreviewUpdate); connect(ui->matchCase, &QCheckBox::toggled, this, &MassReplaceView::requestPreviewUpdate); requestPreviewUpdate(); - } - else - { + } else { disconnect(ui->searchText, &QLineEdit::textEdited, this, &MassReplaceView::requestPreviewUpdate); disconnect(ui->replaceText, &QLineEdit::textEdited, this, &MassReplaceView::requestPreviewUpdate); disconnect(ui->useRegExps, &QCheckBox::toggled, this, &MassReplaceView::requestPreviewUpdate); @@ -903,9 +877,9 @@ void MassReplaceView::requestReplace() { - QString s=ui->searchText->text(); - QString r=ui->replaceText->text(); - + QString s = ui->searchText->text(); + QString r = ui->replaceText->text(); + if (s.isEmpty()) return; @@ -928,16 +902,15 @@ QString FileSearchTab::dbusObjectPath() { - QString FILESEARCH_PATH=QStringLiteral("/ThisIsWhatYouWant/FileSearch/"); - if ( m_dbusId==-1 ) - { + QString FILESEARCH_PATH = QStringLiteral("/ThisIsWhatYouWant/FileSearch/"); + if (m_dbusId == -1) { new FileSearchAdaptor(this); - int i=0; - while(i idsForLangWord(const QString& lang, const QString& word) const; QByteArray id(int index) const; QStringList terms(const QByteArray& id, const QString& lang) const; void setTerm(const QByteArray& id, QString lang, int i, const QString& term); void rmTerm(const QByteArray& id, QString lang, int i); - QString subjectField(const QByteArray& id, const QString& lang=QString()) const; + QString subjectField(const QByteArray& id, const QString& lang = QString()) const; void setSubjectField(const QByteArray& id, const QString& lang, const QString& value); - QString definition(const QByteArray& id, const QString& lang=QString()) const; + QString definition(const QByteArray& id, const QString& lang = QString()) const; void setDefinition(const QByteArray& id, const QString& lang, const QString& value); private: @@ -122,7 +128,10 @@ public: QStringList subjectFields() const; - int size() const{return m_entries.size();} + int size() const + { + return m_entries.size(); + } void clear(); @@ -132,10 +141,13 @@ //in-memory changing QByteArray generateNewId(); - void append(const QString& _english,const QString& _target); + void append(const QString& _english, const QString& _target); void removeEntry(const QByteArray& id); - void forceChangeSignal(){emit changed();} - void setClean(bool ); + void forceChangeSignal() + { + emit changed(); + } + void setClean(bool); QByteArray append(const QStringList& sourceTerms, const QStringList& targetTerms); @@ -158,11 +170,11 @@ QList m_idsForEntriesById; - QMap< QString, QMultiHash > idsByLangWord; + QMap< QString, QMultiHash > idsByLangWord; - QMultiHash wordHash_; + QMultiHash wordHash_; QList termList_; - QMap< QString, QMultiHash > langWordEntry_; + QMap< QString, QMultiHash > langWordEntry_; QStringList subjectFields_;//first entry should be empty //for delayed saving @@ -182,29 +194,28 @@ Q_OBJECT public: - enum Columns - { + enum Columns { ID = 0, English, Target, SubjectField, GlossaryModelColumnCount }; GlossaryModel(QObject* parent/*, Glossary* glossary*/); - ~GlossaryModel(){} + ~GlossaryModel() {} //QModelIndex index (int row, int column, const QModelIndex & parent = QModelIndex() ) const; - int rowCount(const QModelIndex& parent=QModelIndex()) const; - int columnCount(const QModelIndex& parent=QModelIndex()) const; - QVariant data(const QModelIndex&, int role=Qt::DisplayRole) const; - QVariant headerData(int section,Qt::Orientation, int role = Qt::DisplayRole ) const; + int rowCount(const QModelIndex& parent = QModelIndex()) const; + int columnCount(const QModelIndex& parent = QModelIndex()) const; + QVariant data(const QModelIndex&, int role = Qt::DisplayRole) const; + QVariant headerData(int section, Qt::Orientation, int role = Qt::DisplayRole) const; //Qt::ItemFlags flags(const QModelIndex&) const; bool canFetchMore(const QModelIndex& parent) const; void fetchMore(const QModelIndex& parent); - - bool removeRows(int row, int count, const QModelIndex& parent=QModelIndex()); + + bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex()); //bool insertRows(int row,int count,const QModelIndex& parent=QModelIndex()); QByteArray appendRow(const QString& _english, const QString& _target); @@ -221,10 +232,13 @@ { Q_OBJECT public: - GlossarySortFilterProxyModel(QObject* parent=0) - : QSortFilterProxyModel(parent) + GlossarySortFilterProxyModel(QObject* parent = 0) + : QSortFilterProxyModel(parent) {} - Qt::ItemFlags flags(const QModelIndex&) const {return Qt::ItemIsSelectable|Qt::ItemIsEnabled;} + Qt::ItemFlags flags(const QModelIndex&) const + { + return Qt::ItemIsSelectable | Qt::ItemIsEnabled; + } void fetchMore(const QModelIndex& parent); public slots: diff --git a/src/glossary/glossary.cpp b/src/glossary/glossary.cpp --- a/src/glossary/glossary.cpp +++ b/src/glossary/glossary.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -43,14 +43,14 @@ using namespace GlossaryNS; -static const QString defaultLang=QStringLiteral("en_US"); -static const QString xmlLang=QStringLiteral("xml:lang"); -static const QString ntig=QStringLiteral("ntig"); -static const QString tig=QStringLiteral("tig"); -static const QString termGrp=QStringLiteral("termGrp"); -static const QString langSet=QStringLiteral("langSet"); -static const QString term=QStringLiteral("term"); -static const QString id=QStringLiteral("id"); +static const QString defaultLang = QStringLiteral("en_US"); +static const QString xmlLang = QStringLiteral("xml:lang"); +static const QString ntig = QStringLiteral("ntig"); +static const QString tig = QStringLiteral("tig"); +static const QString termGrp = QStringLiteral("termGrp"); +static const QString langSet = QStringLiteral("langSet"); +static const QString term = QStringLiteral("term"); +static const QString id = QStringLiteral("id"); @@ -61,61 +61,59 @@ Glossary::Glossary(QObject* parent) - : QObject(parent) - , m_clean(true) + : QObject(parent) + , m_clean(true) { } //BEGIN DISK bool Glossary::load(const QString& newPath) { - QTime a;a.start(); + QTime a; a.start(); //BEGIN NEW - QIODevice* device=new QFile(newPath); - if (!device->open(QFile::ReadOnly | QFile::Text)) - { + QIODevice* device = new QFile(newPath); + if (!device->open(QFile::ReadOnly | QFile::Text)) { delete device; //return; - device=new QBuffer(); + device = new QBuffer(); static_cast(device)->setData(QByteArray( -"\n" -"\n" -"\n" -" \n" -" \n" -" \n" -" \n" -"\n" -)); + "\n" + "\n" + "\n" + " \n" + " \n" + " \n" + " \n" + "\n" + )); } QXmlSimpleReader reader; //reader.setFeature("http://qtsoftware.com/xml/features/report-whitespace-only-CharData",true); - reader.setFeature("http://xml.org/sax/features/namespaces",false); + reader.setFeature("http://xml.org/sax/features/namespaces", false); QXmlInputSource source(device); QDomDocument newDoc; QString errorMsg; int errorLine;//+errorColumn; - bool success=newDoc.setContent(&source, &reader, &errorMsg, &errorLine/*,errorColumn*/); + bool success = newDoc.setContent(&source, &reader, &errorMsg, &errorLine/*,errorColumn*/); delete device; - if (!success) - { - qCWarning(LOKALIZE_LOG)<50) qCDebug(LOKALIZE_LOG)<<"glossary loaded in"< 50) qCDebug(LOKALIZE_LOG) << "glossary loaded in" << a.elapsed(); return true; } bool Glossary::save() { if (m_path.isEmpty()) return false; - - QFile* device=new QFile(m_path); - if (!device->open(QFile::WriteOnly | QFile::Truncate)) - { + + QFile* device = new QFile(m_path); + if (!device->open(QFile::WriteOnly | QFile::Truncate)) { device->deleteLater(); return false; } QTextStream stream(device); - m_doc.save(stream,2); + m_doc.save(stream, 2); device->deleteLater(); @@ -159,7 +156,7 @@ void Glossary::setClean(bool clean) { - m_clean=clean; + m_clean = clean; emit changed();//may be emitted multiple times in a row. so what? :) } @@ -171,7 +168,7 @@ void GlossarySortFilterProxyModel::setFilterRegExp(const QString& s) { if (!sourceModel()) - return; + return; //static const QRegExp lettersOnly("^[a-z]"); QSortFilterProxyModel::setFilterRegExp(s); @@ -181,27 +178,26 @@ void GlossarySortFilterProxyModel::fetchMore(const QModelIndex&) { - int expectedCount=rowCount()+FETCH_SIZE/2; - while (rowCount(QModelIndex())canFetchMore(QModelIndex())) - { + int expectedCount = rowCount() + FETCH_SIZE / 2; + while (rowCount(QModelIndex()) < expectedCount && sourceModel()->canFetchMore(QModelIndex())) { sourceModel()->fetchMore(QModelIndex()); //qCDebug(LOKALIZE_LOG)<<"filter:"<rowCount(); - QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents|QEventLoop::ExcludeSocketNotifiers); + QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents | QEventLoop::ExcludeSocketNotifiers); } } GlossaryModel::GlossaryModel(QObject* parent) - : QAbstractListModel(parent) - , m_visibleCount(0) - , m_glossary(Project::instance()->glossary()) + : QAbstractListModel(parent) + , m_visibleCount(0) + , m_glossary(Project::instance()->glossary()) { connect(m_glossary, &Glossary::loaded, this, &GlossaryModel::forceReset); } void GlossaryModel::forceReset() { beginResetModel(); - m_visibleCount=0; + m_visibleCount = 0; endResetModel(); } @@ -212,9 +208,9 @@ void GlossaryModel::fetchMore(const QModelIndex& parent) { - int newVisibleCount=qMin(m_visibleCount+FETCH_SIZE,m_glossary->size()); - beginInsertRows(parent, m_visibleCount, newVisibleCount-1); - m_visibleCount=newVisibleCount; + int newVisibleCount = qMin(m_visibleCount + FETCH_SIZE, m_glossary->size()); + beginInsertRows(parent, m_visibleCount, newVisibleCount - 1); + m_visibleCount = newVisibleCount; endInsertRows(); } @@ -225,17 +221,16 @@ return m_glossary->size();//m_visibleCount; } -QVariant GlossaryModel::headerData( int section, Qt::Orientation /*orientation*/, int role) const +QVariant GlossaryModel::headerData(int section, Qt::Orientation /*orientation*/, int role) const { - if (role!=Qt::DisplayRole) + if (role != Qt::DisplayRole) return QVariant(); - switch (section) - { - //case ID: return i18nc("@title:column","ID"); - case English: return i18nc("@title:column Original text","Source");; - case Target: return i18nc("@title:column Text in target language","Target"); - case SubjectField: return i18nc("@title:column","Subject Field"); + switch (section) { + //case ID: return i18nc("@title:column","ID"); + case English: return i18nc("@title:column Original text", "Source");; + case Target: return i18nc("@title:column Text in target language", "Target"); + case SubjectField: return i18nc("@title:column", "Subject Field"); } return QVariant(); } @@ -245,20 +240,19 @@ //if (role==Qt::SizeHintRole) // return QVariant(QSize(50, 30)); - if (role!=Qt::DisplayRole) + if (role != Qt::DisplayRole) return QVariant(); - static const QString nl=QStringLiteral(" ")+QChar(0x00B7)+' '; - static Project* project=Project::instance(); - Glossary* glossary=m_glossary; - - QByteArray id=glossary->id(index.row()); - switch (index.column()) - { - case ID: return id; - case English: return glossary->terms(id, project->sourceLangCode()).join(nl); - case Target: return glossary->terms(id, project->targetLangCode()).join(nl); - case SubjectField: return glossary->subjectField(id); + static const QString nl = QStringLiteral(" ") + QChar(0x00B7) + ' '; + static Project* project = Project::instance(); + Glossary* glossary = m_glossary; + + QByteArray id = glossary->id(index.row()); + switch (index.column()) { + case ID: return id; + case English: return glossary->terms(id, project->sourceLangCode()).join(nl); + case Target: return glossary->terms(id, project->targetLangCode()).join(nl); + case SubjectField: return glossary->subjectField(id); } return QVariant(); } @@ -293,75 +287,68 @@ QByteArray Glossary::generateNewId() { // generate unique ID - int idNumber=0; + int idNumber = 0; QList busyIdNumbers; QString authorId(Settings::authorName().toLower()); - authorId.replace(' ','_'); - QRegExp rx('^'%authorId%QStringLiteral("\\-([0-9]*)$")); + authorId.replace(' ', '_'); + QRegExp rx('^' % authorId % QStringLiteral("\\-([0-9]*)$")); - foreach(const QByteArray& id, m_idsForEntriesById) - { + foreach (const QByteArray& id, m_idsForEntriesById) { if (rx.exactMatch(QString::fromLatin1(id))) busyIdNumbers.append(rx.cap(1).toInt()); } - int i=removedIds.size(); - while(--i>=0) - { + int i = removedIds.size(); + while (--i >= 0) { if (rx.exactMatch(QString::fromLatin1(removedIds.at(i)))) busyIdNumbers.append(rx.cap(1).toInt()); } - if (!busyIdNumbers.isEmpty()) - { + if (!busyIdNumbers.isEmpty()) { qSort(busyIdNumbers); while (busyIdNumbers.contains(idNumber)) ++idNumber; } - return authorId.toLatin1()+'-'+QByteArray::number(idNumber); + return authorId.toLatin1() + '-' + QByteArray::number(idNumber); } QStringList Glossary::subjectFields() const { QSet result; - foreach(const QByteArray& id, m_idsForEntriesById) + foreach (const QByteArray& id, m_idsForEntriesById) result.insert(subjectField(id)); return result.toList(); } QByteArray Glossary::id(int index) const { - if (index as well - QDomElement& termElement) + QDomElement& ourLangSetElement, + QDomElement& tigElement, //<-- can point to as well + QDomElement& termElement) { - QString minusLang=lang; minusLang.replace('_', '-'); - QStringRef soleLang=lang.leftRef(2); + QString minusLang = lang; minusLang.replace('_', '-'); + QStringRef soleLang = lang.leftRef(2); //qCDebug(LOKALIZE_LOG)<<"started walking over"<sourceLangCode(); - foreach(const QString& termText, terms(entryId, sourceLangCode)) - { - foreach(const QString& word, termText.split(' ',QString::SkipEmptyParts)) - idsByLangWord[sourceLangCode].insert(stem(sourceLangCode,word),entryId); + QString sourceLangCode = Project::instance()->sourceLangCode(); + foreach (const QString& termText, terms(entryId, sourceLangCode)) { + foreach (const QString& word, termText.split(' ', QString::SkipEmptyParts)) + idsByLangWord[sourceLangCode].insert(stem(sourceLangCode, word), entryId); } } void Glossary::unhashTermEntry(const QDomElement& termEntry) { - QByteArray entryId=termEntry.attribute(::id).toLatin1(); + QByteArray entryId = termEntry.attribute(::id).toLatin1(); m_entriesById.remove(entryId); - QString sourceLangCode=Project::instance()->sourceLangCode(); - foreach(const QString& termText, terms(entryId, sourceLangCode)) - { - foreach(const QString& word, termText.split(' ',QString::SkipEmptyParts)) - idsByLangWord[sourceLangCode].remove(stem(sourceLangCode,word),entryId); + QString sourceLangCode = Project::instance()->sourceLangCode(); + foreach (const QString& termText, terms(entryId, sourceLangCode)) { + foreach (const QString& word, termText.split(' ', QString::SkipEmptyParts)) + idsByLangWord[sourceLangCode].remove(stem(sourceLangCode, word), entryId); } } #if 0 void Glossary::hashTermEntry(int index) { - Q_ASSERT(indexsourceLangCode(),word),index); + Q_ASSERT(index < termList.size()); + foreach (const QString& term, termList_.at(index).english) { + foreach (const QString& word, term.split(' ', QString::SkipEmptyParts)) + wordHash_.insert(stem(Project::instance()->sourceLangCode(), word), index); } } void Glossary::unhashTermEntry(int index) { - Q_ASSERT(indexsourceLangCode(),word),index); + Q_ASSERT(index < termList.size()); + foreach (const QString& term, termList_.at(index).english) { + foreach (const QString& word, term.split(' ', QString::SkipEmptyParts)) + wordHash_.remove(stem(Project::instance()->sourceLangCode(), word), index); } } #endif @@ -656,23 +624,23 @@ m_entriesById.remove(id); unhashTermEntry(entry); - m_idsForEntriesById=m_entriesById.keys(); + m_idsForEntriesById = m_entriesById.keys(); removedIds.append(id); //for new id generation goodness setClean(false); } static void appendTerm(QDomElement langSetElem, const QString& termText) { - QDomDocument doc=langSetElem.ownerDocument(); -/* - QDomElement ntigElement=doc.createElement(ntig); langSetElem.appendChild(ntigElement); - QDomElement termGrpElement=doc.createElement(termGrp); ntigElement.appendChild(termGrpElement); - QDomElement termElement=doc.createElement(term); termGrpElement.appendChild(termElement); - termElement.appendChild(doc.createTextNode(termText)); -*/ - QDomElement tigElement=doc.createElement(tig); langSetElem.appendChild(tigElement); - QDomElement termElement=doc.createElement(term); tigElement.appendChild(termElement); + QDomDocument doc = langSetElem.ownerDocument(); + /* + QDomElement ntigElement=doc.createElement(ntig); langSetElem.appendChild(ntigElement); + QDomElement termGrpElement=doc.createElement(termGrp); ntigElement.appendChild(termGrpElement); + QDomElement termElement=doc.createElement(term); termGrpElement.appendChild(termElement); + termElement.appendChild(doc.createTextNode(termText)); + */ + QDomElement tigElement = doc.createElement(tig); langSetElem.appendChild(tigElement); + QDomElement termElement = doc.createElement(term); tigElement.appendChild(termElement); termElement.appendChild(doc.createTextNode(termText)); } @@ -682,26 +650,26 @@ return QByteArray(); setClean(false); - QDomElement termEntry=m_doc.createElement(QStringLiteral("termEntry")); + QDomElement termEntry = m_doc.createElement(QStringLiteral("termEntry")); m_doc.elementsByTagName(QStringLiteral("body")).at(0).appendChild(termEntry); //m_entries=m_doc.elementsByTagName("termEntry"); - QByteArray newId=generateNewId(); + QByteArray newId = generateNewId(); termEntry.setAttribute(::id, QString::fromLatin1(newId)); - QDomElement sourceElem=m_doc.createElement(langSet); termEntry.appendChild(sourceElem); - sourceElem.setAttribute(xmlLang, Project::instance()->sourceLangCode().replace('_','-')); + QDomElement sourceElem = m_doc.createElement(langSet); termEntry.appendChild(sourceElem); + sourceElem.setAttribute(xmlLang, Project::instance()->sourceLangCode().replace('_', '-')); foreach (QString sourceTerm, sourceTerms) appendTerm(sourceElem, sourceTerm); - QDomElement targetElem=m_doc.createElement(langSet); termEntry.appendChild(targetElem); + QDomElement targetElem = m_doc.createElement(langSet); termEntry.appendChild(targetElem); targetElem.setAttribute(xmlLang, Project::instance()->targetLangCode().replace('_', '-')); foreach (QString targetTerm, targetTerms) appendTerm(targetElem, targetTerm); hashTermEntry(termEntry); - m_idsForEntriesById=m_entriesById.keys(); + m_idsForEntriesById = m_entriesById.keys(); return newId; } @@ -725,19 +693,19 @@ wordHash_.clear(); termList_.clear(); langWordEntry_.clear(); - subjectFields_=QStringList(QString()); + subjectFields_ = QStringList(QString()); m_doc.clear(); } bool GlossaryModel::removeRows(int row, int count, const QModelIndex& parent) { - beginRemoveRows(parent,row,row+count-1); + beginRemoveRows(parent, row, row + count - 1); - Glossary* glossary=Project::instance()->glossary(); - int i=row+count; - while (--i>=row) + Glossary* glossary = Project::instance()->glossary(); + int i = row + count; + while (--i >= row) glossary->removeEntry(glossary->id(i)); endRemoveRows(); @@ -750,14 +718,13 @@ // return false; QByteArray GlossaryModel::appendRow(const QString& _english, const QString& _target) { - bool notify=!canFetchMore(QModelIndex()); + bool notify = !canFetchMore(QModelIndex()); if (notify) - beginInsertRows(QModelIndex(),rowCount(),rowCount()); + beginInsertRows(QModelIndex(), rowCount(), rowCount()); - QByteArray id=m_glossary->append(QStringList(_english), QStringList(_target)); + QByteArray id = m_glossary->append(QStringList(_english), QStringList(_target)); - if (notify) - { + if (notify) { m_visibleCount++; endInsertRows(); } diff --git a/src/glossary/glossaryview.h b/src/glossary/glossaryview.h --- a/src/glossary/glossaryview.h +++ b/src/glossary/glossaryview.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -37,16 +37,17 @@ class QScrollArea; #include -namespace GlossaryNS { +namespace GlossaryNS +{ class Glossary; #define GLOSSARY_SHORTCUTS 11 class GlossaryView: public QDockWidget { Q_OBJECT public: - GlossaryView(QWidget*,Catalog*,const QVector&); + GlossaryView(QWidget*, Catalog*, const QVector&); ~GlossaryView(); diff --git a/src/glossary/glossaryview.cpp b/src/glossary/glossaryview.cpp --- a/src/glossary/glossaryview.cpp +++ b/src/glossary/glossaryview.cpp @@ -54,38 +54,38 @@ using namespace GlossaryNS; -GlossaryView::GlossaryView(QWidget* parent,Catalog* catalog,const QVector& actions) - : QDockWidget ( i18nc("@title:window","Glossary"), parent) - , m_browser(new QScrollArea(this)) - , m_catalog(catalog) - , m_flowLayout(new FlowLayout(FlowLayout::glossary,/*who gets signals*/this,actions,0,10)) - , m_glossary(Project::instance()->glossary()) - , m_rxClean(Project::instance()->markup()%'|'%Project::instance()->accel())//cleaning regexp; NOTE isEmpty()? - , m_rxSplit(QStringLiteral("\\W|\\d"))//splitting regexp - , m_currentIndex(-1) - , m_normTitle(i18nc("@title:window","Glossary")) - , m_hasInfoTitle(m_normTitle+QStringLiteral(" [*]")) - , m_hasInfo(false) +GlossaryView::GlossaryView(QWidget* parent, Catalog* catalog, const QVector& actions) + : QDockWidget(i18nc("@title:window", "Glossary"), parent) + , m_browser(new QScrollArea(this)) + , m_catalog(catalog) + , m_flowLayout(new FlowLayout(FlowLayout::glossary,/*who gets signals*/this, actions, 0, 10)) + , m_glossary(Project::instance()->glossary()) + , m_rxClean(Project::instance()->markup() % '|' % Project::instance()->accel()) //cleaning regexp; NOTE isEmpty()? + , m_rxSplit(QStringLiteral("\\W|\\d"))//splitting regexp + , m_currentIndex(-1) + , m_normTitle(i18nc("@title:window", "Glossary")) + , m_hasInfoTitle(m_normTitle + QStringLiteral(" [*]")) + , m_hasInfo(false) { setObjectName(QStringLiteral("glossaryView")); - QWidget* w=new QWidget(m_browser); + QWidget* w = new QWidget(m_browser); m_browser->setWidget(w); m_browser->setWidgetResizable(true); w->setLayout(m_flowLayout); w->show(); - setToolTip(i18nc("@info:tooltip","

Translations for common terms appear here.

" - "

Press shortcut displayed near the term to insert its translation.

" - "

Use context menu to add new entry (tip: select words in original and translation fields before calling Define new term).

")); + setToolTip(i18nc("@info:tooltip", "

Translations for common terms appear here.

" + "

Press shortcut displayed near the term to insert its translation.

" + "

Use context menu to add new entry (tip: select words in original and translation fields before calling Define new term).

")); setWidget(m_browser); m_browser->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); m_browser->setAutoFillBackground(true); m_browser->setBackgroundRole(QPalette::Background); m_rxClean.setMinimal(true); - connect (m_glossary, &Glossary::changed, this, QOverload<>::of(&GlossaryView::slotNewEntryDisplayed), Qt::QueuedConnection); + connect(m_glossary, &Glossary::changed, this, QOverload<>::of(&GlossaryView::slotNewEntryDisplayed), Qt::QueuedConnection); } GlossaryView::~GlossaryView() @@ -101,7 +101,7 @@ // event->acceptProposedAction(); // };*/ // } -// +// // void GlossaryView::dropEvent(QDropEvent *event) // { // event->acceptProposedAction();*/ @@ -115,23 +115,23 @@ void GlossaryView::slotNewEntryDisplayed(DocPosition pos) { //qCWarning(LOKALIZE_LOG)<<"\n\n\n\nstart"<numberOfEntries()<=pos.entry) + if (pos.entry == -1 || m_catalog->numberOfEntries() <= pos.entry) return;//because of Qt::QueuedConnection //if (!toggleViewAction()->isChecked()) // return; - Glossary& glossary=*m_glossary; + Glossary& glossary = *m_glossary; - QString source=m_catalog->source(pos); - QString sourceLowered=source.toLower(); - QString msg=sourceLowered; + QString source = m_catalog->source(pos); + QString sourceLowered = source.toLower(); + QString msg = sourceLowered; msg.remove(m_rxClean); QString msgStemmed; @@ -144,16 +144,15 @@ // pos=accel.pos(1); // } - QString sourceLangCode=Project::instance()->sourceLangCode(); + QString sourceLangCode = Project::instance()->sourceLangCode(); QList termIds; - foreach (const QString& w, msg.split(m_rxSplit,QString::SkipEmptyParts)) - { - QString word=stem(sourceLangCode,w); - QList indexes=glossary.idsForLangWord(sourceLangCode,word); + foreach (const QString& w, msg.split(m_rxSplit, QString::SkipEmptyParts)) { + QString word = stem(sourceLangCode, w); + QList indexes = glossary.idsForLangWord(sourceLangCode, word); //if (indexes.size()) - //qCWarning(LOKALIZE_LOG)<<"found entry for:" <clearTerms(); - bool found=false; + bool found = false; //m_flowLayout->setEnabled(false); - foreach (const QByteArray& termId, termIds.toSet()) - { + foreach (const QByteArray& termId, termIds.toSet()) { // now check which of them are really hits... - foreach (const QString& enTerm, glossary.terms(termId, sourceLangCode)) - { + foreach (const QString& enTerm, glossary.terms(termId, sourceLangCode)) { // ...and if so, which part of termEn list we must thank for match ... - bool ok=msg.contains(enTerm);//,//Qt::CaseInsensitive //we lowered terms on load - if (!ok) - { + bool ok = msg.contains(enTerm); //,//Qt::CaseInsensitive //we lowered terms on load + if (!ok) { QString enTermStemmed; - foreach (const QString& word, enTerm.split(m_rxSplit,QString::SkipEmptyParts)) - enTermStemmed+=stem(sourceLangCode,word)+' '; - ok=msgStemmed.contains(enTermStemmed); + foreach (const QString& word, enTerm.split(m_rxSplit, QString::SkipEmptyParts)) + enTermStemmed += stem(sourceLangCode, word) + ' '; + ok = msgStemmed.contains(enTermStemmed); } - if (ok) - { + if (ok) { //insert it into label - found=true; - int pos=sourceLowered.indexOf(enTerm); - m_flowLayout->addTerm(enTerm,termId,/*uppercase*/pos!=-1 && source.at(pos).isUpper()); + found = true; + int pos = sourceLowered.indexOf(enTerm); + m_flowLayout->addTerm(enTerm, termId,/*uppercase*/pos != -1 && source.at(pos).isUpper()); break; } } } //m_flowLayout->setEnabled(true); if (!found) clear(); - else if (!m_hasInfo) - { - m_hasInfo=true; + else if (!m_hasInfo) { + m_hasInfo = true; setWindowTitle(m_hasInfoTitle); } setUpdatesEnabled(true); } void GlossaryView::clear() { - if (m_hasInfo) - { + if (m_hasInfo) { m_flowLayout->clearTerms(); - m_hasInfo=false; + m_hasInfo = false; setWindowTitle(m_normTitle); } } diff --git a/src/glossary/glossarywindow.h b/src/glossary/glossarywindow.h --- a/src/glossary/glossarywindow.h +++ b/src/glossary/glossarywindow.h @@ -41,34 +41,39 @@ { Q_OBJECT public: - AuxTextEdit(QWidget* parent=0): KTextEdit(parent){} + AuxTextEdit(QWidget* parent = 0): KTextEdit(parent) {} - void focusOutEvent(QFocusEvent* e){Q_UNUSED(e); emit editingFinished();} + void focusOutEvent(QFocusEvent* e) + { + Q_UNUSED(e); + emit editingFinished(); + } signals: void editingFinished(); }; class TermListView: public QListView { Q_OBJECT public: - explicit TermListView(QWidget* parent = 0):QListView(parent){} + explicit TermListView(QWidget* parent = 0): QListView(parent) {} public slots: void rmTerms(); void addTerm(); }; -namespace GlossaryNS { +namespace GlossaryNS +{ class GlossaryTreeView; class Glossary; class TermsListModel; class GlossarySortFilterProxyModel; class GlossaryWindow: public KMainWindow { -Q_OBJECT + Q_OBJECT public: GlossaryWindow(QWidget *parent = 0); ~GlossaryWindow(); @@ -109,10 +114,10 @@ class GlossaryTreeView: public QTreeView { -Q_OBJECT + Q_OBJECT public: GlossaryTreeView(QWidget *parent = 0); - ~GlossaryTreeView(){} + ~GlossaryTreeView() {} void currentChanged(const QModelIndex& current, const QModelIndex& previous); void selectRow(int i); @@ -128,7 +133,7 @@ { Q_OBJECT public: - TermsListModel(Glossary* glossary, const QString& lang, QObject* parent=0): QStringListModel(parent), m_glossary(glossary), m_lang(lang){} + TermsListModel(Glossary* glossary, const QString& lang, QObject* parent = 0): QStringListModel(parent), m_glossary(glossary), m_lang(lang) {} bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole); bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex()); diff --git a/src/glossary/glossarywindow.cpp b/src/glossary/glossarywindow.cpp --- a/src/glossary/glossarywindow.cpp +++ b/src/glossary/glossarywindow.cpp @@ -52,28 +52,27 @@ //BEGIN GlossaryTreeView GlossaryTreeView::GlossaryTreeView(QWidget *parent) - : QTreeView(parent) + : QTreeView(parent) { setSortingEnabled(true); sortByColumn(GlossaryModel::English, Qt::AscendingOrder); setItemsExpandable(false); setAllColumnsShowFocus(true); -/* - setSelectionMode(QAbstractItemView::ExtendedSelection); - setSelectionBehavior(QAbstractItemView::SelectRows);*/ + /* + setSelectionMode(QAbstractItemView::ExtendedSelection); + setSelectionBehavior(QAbstractItemView::SelectRows);*/ } static QByteArray modelIndexToId(const QModelIndex& item) { - return item.sibling(item.row(),0).data(Qt::DisplayRole).toByteArray(); + return item.sibling(item.row(), 0).data(Qt::DisplayRole).toByteArray(); } void GlossaryTreeView::currentChanged(const QModelIndex& current, const QModelIndex&/* previous*/) { - if (current.isValid()) - { + if (current.isValid()) { //QModelIndex item=static_cast(model())->mapToSource(current); //emit currentChanged(item.row()); emit currentChanged(modelIndexToId(current)); @@ -83,11 +82,11 @@ void GlossaryTreeView::selectRow(int i) { - QSortFilterProxyModel* proxyModel=static_cast(model()); - GlossaryModel* sourceModel=static_cast(proxyModel->sourceModel()); + QSortFilterProxyModel* proxyModel = static_cast(model()); + GlossaryModel* sourceModel = static_cast(proxyModel->sourceModel()); //sourceModel->forceReset(); - setCurrentIndex(proxyModel->mapFromSource(sourceModel->index(i,0))); + setCurrentIndex(proxyModel->mapFromSource(sourceModel->index(i, 0))); } @@ -105,37 +104,37 @@ //Q_OBJECT SubjectFieldModel(QObject* parent); - ~SubjectFieldModel(){} + ~SubjectFieldModel() {} - QModelIndex index (int row, int column, const QModelIndex& parent=QModelIndex()) const; + QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const; QModelIndex parent(const QModelIndex&) const; - int rowCount(const QModelIndex& parent=QModelIndex()) const; - int columnCount(const QModelIndex& parent=QModelIndex()) const; - QVariant data(const QModelIndex&,int role=Qt::DisplayRole) const; - bool setData (const QModelIndex&,const QVariant&,int role=Qt::EditRole); - bool setItemData(const QModelIndex& index, const QMap& roles); - bool insertRows(int row, int count, const QModelIndex& parent=QModelIndex()); + int rowCount(const QModelIndex& parent = QModelIndex()) const; + int columnCount(const QModelIndex& parent = QModelIndex()) const; + QVariant data(const QModelIndex&, int role = Qt::DisplayRole) const; + bool setData(const QModelIndex&, const QVariant&, int role = Qt::EditRole); + bool setItemData(const QModelIndex& index, const QMap& roles); + bool insertRows(int row, int count, const QModelIndex& parent = QModelIndex()); Qt::ItemFlags flags(const QModelIndex&) const; -/*private: - Catalog* m_catalog;*/ + /*private: + Catalog* m_catalog;*/ }; inline SubjectFieldModel::SubjectFieldModel(QObject* parent) - : QAbstractItemModel(parent) + : QAbstractItemModel(parent) // , m_catalog(catalog) { } -QModelIndex SubjectFieldModel::index (int row,int column,const QModelIndex& /*parent*/) const +QModelIndex SubjectFieldModel::index(int row, int column, const QModelIndex& /*parent*/) const { - return createIndex (row, column); + return createIndex(row, column); } Qt::ItemFlags SubjectFieldModel::flags(const QModelIndex&) const { - return Qt::ItemIsSelectable|Qt::ItemIsEditable|Qt::ItemIsEnabled; + return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled; } QModelIndex SubjectFieldModel::parent(const QModelIndex& /*index*/) const @@ -165,40 +164,39 @@ return Project::instance()->glossary()->subjectFields.size(); } -QVariant SubjectFieldModel::data(const QModelIndex& index,int role) const +QVariant SubjectFieldModel::data(const QModelIndex& index, int role) const { - if (role==Qt::DisplayRole||role==Qt::EditRole) + if (role == Qt::DisplayRole || role == Qt::EditRole) return Project::instance()->glossary()->subjectFields.at(index.row()); return QVariant(); } bool SubjectFieldModel::insertRows(int row, int count, const QModelIndex& parent) { - beginInsertRows(parent,row,row+count-1); + beginInsertRows(parent, row, row + count - 1); - QStringList& subjectFields=Project::instance()->glossary()->subjectFields; + QStringList& subjectFields = Project::instance()->glossary()->subjectFields; - while (--count>=0) - subjectFields.insert(row+count,QString()); + while (--count >= 0) + subjectFields.insert(row + count, QString()); endInsertRows(); return true; } bool SubjectFieldModel::setData(const QModelIndex& index, const QVariant& value, int role) { - qCDebug(LOKALIZE_LOG)<glossary()->subjectFields; - subjectFields[index.row()]=value.toString(); + qCDebug(LOKALIZE_LOG) << role; + QStringList& subjectFields = Project::instance()->glossary()->subjectFields; + subjectFields[index.row()] = value.toString(); return true; } -bool SubjectFieldModel::setItemData(const QModelIndex& index, const QMap& roles) +bool SubjectFieldModel::setItemData(const QModelIndex& index, const QMap& roles) { - if (roles.contains(Qt::EditRole)) - { - QStringList& subjectFields=Project::instance()->glossary()->subjectFields; - subjectFields[index.row()]=roles.value(Qt::EditRole).toString(); + if (roles.contains(Qt::EditRole)) { + QStringList& subjectFields = Project::instance()->glossary()->subjectFields; + subjectFields[index.row()] = roles.value(Qt::EditRole).toString(); } return true; } @@ -208,115 +206,115 @@ //BEGIN GlossaryWindow GlossaryWindow::GlossaryWindow(QWidget *parent) - : KMainWindow(parent) - , m_browser(new GlossaryTreeView(this)) - , m_proxyModel(new GlossarySortFilterProxyModel(this)) - , m_reactOnSignals(true) + : KMainWindow(parent) + , m_browser(new GlossaryTreeView(this)) + , m_proxyModel(new GlossarySortFilterProxyModel(this)) + , m_reactOnSignals(true) { //setAttribute(Qt::WA_DeleteOnClose, true); setAttribute(Qt::WA_DeleteOnClose, false); - QSplitter* splitter=new QSplitter(Qt::Horizontal,this); + QSplitter* splitter = new QSplitter(Qt::Horizontal, this); setCentralWidget(splitter); m_proxyModel->setFilterKeyColumn(-1); m_proxyModel->setDynamicSortFilter(true);; - GlossaryModel* model=new GlossaryModel(this); + GlossaryModel* model = new GlossaryModel(this); m_proxyModel->setSourceModel(model); m_browser->setModel(m_proxyModel); m_browser->setUniformRowHeights(true); m_browser->setAutoScroll(true); - m_browser->setColumnHidden(GlossaryModel::ID,true); - m_browser->setColumnWidth(GlossaryModel::English, m_browser->columnWidth(GlossaryModel::English)*2); //man this is HACK y - m_browser->setColumnWidth(GlossaryModel::Target, m_browser->columnWidth(GlossaryModel::Target)*2); + m_browser->setColumnHidden(GlossaryModel::ID, true); + m_browser->setColumnWidth(GlossaryModel::English, m_browser->columnWidth(GlossaryModel::English) * 2); //man this is HACK y + m_browser->setColumnWidth(GlossaryModel::Target, m_browser->columnWidth(GlossaryModel::Target) * 2); m_browser->setAlternatingRowColors(true); //left - QWidget* w=new QWidget(splitter); - QVBoxLayout* layout=new QVBoxLayout(w); - m_filterEdit=new QLineEdit(w); + QWidget* w = new QWidget(splitter); + QVBoxLayout* layout = new QVBoxLayout(w); + m_filterEdit = new QLineEdit(w); m_filterEdit->setClearButtonEnabled(true); m_filterEdit->setPlaceholderText(i18n("Quick search...")); m_filterEdit->setFocus(); - m_filterEdit->setToolTip(i18nc("@info:tooltip","Activated by Ctrl+L.")+" "+i18nc("@info:tooltip","Accepts regular expressions")); - new QShortcut(Qt::CTRL+Qt::Key_L,this,SLOT(setFocus()),0,Qt::WidgetWithChildrenShortcut); - connect (m_filterEdit, &QLineEdit::textChanged, m_proxyModel, &GlossaryNS::GlossarySortFilterProxyModel::setFilterRegExp); + m_filterEdit->setToolTip(i18nc("@info:tooltip", "Activated by Ctrl+L.") + " " + i18nc("@info:tooltip", "Accepts regular expressions")); + new QShortcut(Qt::CTRL + Qt::Key_L, this, SLOT(setFocus()), 0, Qt::WidgetWithChildrenShortcut); + connect(m_filterEdit, &QLineEdit::textChanged, m_proxyModel, &GlossaryNS::GlossarySortFilterProxyModel::setFilterRegExp); layout->addWidget(m_filterEdit); layout->addWidget(m_browser); { - QPushButton* addBtn=new QPushButton(w); + QPushButton* addBtn = new QPushButton(w); connect(addBtn, &QPushButton::clicked, this, QOverload<>::of(&GlossaryWindow::newTermEntry)); - QPushButton* rmBtn=new QPushButton(w); + QPushButton* rmBtn = new QPushButton(w); connect(rmBtn, &QPushButton::clicked, this, QOverload<>::of(&GlossaryWindow::rmTermEntry)); #ifndef NOKDE KGuiItem::assign(addBtn, KStandardGuiItem::add()); - KGuiItem::assign( rmBtn, KStandardGuiItem::remove()); + KGuiItem::assign(rmBtn, KStandardGuiItem::remove()); #else addBtn->setText(QApplication::translate("KStandardGuiItem", "Add")); - rmBtn->setText( QApplication::translate("KStandardGuiItem", "Remove")); + rmBtn->setText(QApplication::translate("KStandardGuiItem", "Remove")); #endif - QPushButton* restoreBtn=new QPushButton(i18nc("@action:button reloads glossary from disk","Restore from disk"),w); - restoreBtn->setToolTip(i18nc("@info:tooltip","Reload glossary from disk, discarding any changes")); + QPushButton* restoreBtn = new QPushButton(i18nc("@action:button reloads glossary from disk", "Restore from disk"), w); + restoreBtn->setToolTip(i18nc("@info:tooltip", "Reload glossary from disk, discarding any changes")); connect(restoreBtn, &QPushButton::clicked, this, &GlossaryWindow::restore); - QWidget* btns=new QWidget(w); - QHBoxLayout* btnsLayout=new QHBoxLayout(btns); + QWidget* btns = new QWidget(w); + QHBoxLayout* btnsLayout = new QHBoxLayout(btns); btnsLayout->addWidget(addBtn); btnsLayout->addWidget(rmBtn); btnsLayout->addWidget(restoreBtn); layout->addWidget(btns); //QWidget::setTabOrder(m_browser,addBtn); - QWidget::setTabOrder(addBtn,rmBtn); - QWidget::setTabOrder(rmBtn,restoreBtn); - QWidget::setTabOrder(restoreBtn,m_filterEdit); + QWidget::setTabOrder(addBtn, rmBtn); + QWidget::setTabOrder(rmBtn, restoreBtn); + QWidget::setTabOrder(restoreBtn, m_filterEdit); } - QWidget::setTabOrder(m_filterEdit,m_browser); + QWidget::setTabOrder(m_filterEdit, m_browser); splitter->addWidget(w); //right - m_editor=new QWidget(splitter); + m_editor = new QWidget(splitter); m_editor->hide(); Ui_TermEdit ui_termEdit; ui_termEdit.setupUi(m_editor); splitter->addWidget(m_editor); - Project* project=Project::instance(); - m_sourceTermsModel=new TermsListModel(project->glossary(), project->sourceLangCode(), this); - m_targetTermsModel=new TermsListModel(project->glossary(), project->targetLangCode(), this); + Project* project = Project::instance(); + m_sourceTermsModel = new TermsListModel(project->glossary(), project->sourceLangCode(), this); + m_targetTermsModel = new TermsListModel(project->glossary(), project->targetLangCode(), this); ui_termEdit.sourceTermsView->setModel(m_sourceTermsModel); ui_termEdit.targetTermsView->setModel(m_targetTermsModel); - + connect(ui_termEdit.addEngTerm, &QToolButton::clicked, ui_termEdit.sourceTermsView, &TermListView::addTerm); connect(ui_termEdit.remEngTerm, &QToolButton::clicked, ui_termEdit.sourceTermsView, &TermListView::rmTerms); connect(ui_termEdit.addTargetTerm, &QToolButton::clicked, ui_termEdit.targetTermsView, &TermListView::addTerm); connect(ui_termEdit.remTargetTerm, &QToolButton::clicked, ui_termEdit.targetTermsView, &TermListView::rmTerms); - m_sourceTermsView=ui_termEdit.sourceTermsView; - m_targetTermsView=ui_termEdit.targetTermsView; - m_subjectField=ui_termEdit.subjectField; - m_definition=ui_termEdit.definition; - m_definitionLang=ui_termEdit.definitionLang; + m_sourceTermsView = ui_termEdit.sourceTermsView; + m_targetTermsView = ui_termEdit.targetTermsView; + m_subjectField = ui_termEdit.subjectField; + m_definition = ui_termEdit.definition; + m_definitionLang = ui_termEdit.definitionLang; //connect (m_english,SIGNAL(textChanged()), this,SLOT(applyEntryChange())); //connect (m_target,SIGNAL(textChanged()), this,SLOT(applyEntryChange())); //connect (m_definition,SIGNAL(editingFinished()),this,SLOT(applyEntryChange())); //connect (m_definition,SIGNAL(textChanged()),this,SLOT(applyEntryChange())); //connect (m_subjectField,SIGNAL(editTextChanged(QString)),this,SLOT(applyEntryChange())); - connect (m_subjectField->lineEdit(), &QLineEdit::editingFinished, this, &GlossaryWindow::applyEntryChange); + connect(m_subjectField->lineEdit(), &QLineEdit::editingFinished, this, &GlossaryWindow::applyEntryChange); //m_subjectField->addItems(Project::instance()->glossary()->subjectFields()); //m_subjectField->setModel(new SubjectFieldModel(this)); - QStringList subjectFields=Project::instance()->glossary()->subjectFields(); + QStringList subjectFields = Project::instance()->glossary()->subjectFields(); qSort(subjectFields); - QStringListModel* subjectFieldsModel=new QStringListModel(this); + QStringListModel* subjectFieldsModel = new QStringListModel(this); subjectFieldsModel->setStringList(subjectFields); m_subjectField->setModel(subjectFieldsModel); connect(m_browser, QOverload::of(&GlossaryTreeView::currentChanged), this, &GlossaryWindow::currentChanged); @@ -330,7 +328,7 @@ //connect(m_targetTermsModel,SIGNAL(dataChanged(QModelIndex,QModelIndex)),m_browser,SLOT(setFocus())); #ifndef NOKDE - setAutoSaveSettings(QLatin1String("GlossaryWindow"),true); + setAutoSaveSettings(QLatin1String("GlossaryWindow"), true); #endif //Glossary* glossary=Project::instance()->glossary(); /*setCaption(i18nc("@title:window","Glossary"), @@ -356,23 +354,21 @@ else m_editor->show(); - m_id=id; + m_id = id; - m_reactOnSignals=false; + m_reactOnSignals = false; - Project* project=Project::instance(); - Glossary* glossary=project->glossary(); + Project* project = Project::instance(); + Glossary* glossary = project->glossary(); m_subjectField->setCurrentItem(glossary->subjectField(id),/*insert*/true); - - QStringList langsToTry=QStringList(m_defLang)<targetLangCode(); - foreach (const QString& lang, langsToTry) - { - QString d=glossary->definition(m_id, lang); - if (!d.isEmpty()) - { - if (m_defLang!=lang) + + QStringList langsToTry = QStringList(m_defLang) << QStringLiteral("en") << QStringLiteral("en_US") << project->targetLangCode(); + foreach (const QString& lang, langsToTry) { + QString d = glossary->definition(m_id, lang); + if (!d.isEmpty()) { + if (m_defLang != lang) m_definitionLang->setCurrentIndex(LanguageListModel::emptyLangInstance()->sortModelRowForLangCode(lang)); - m_defLang=lang; + m_defLang = lang; break; } } @@ -385,72 +381,69 @@ //m_sourceTermsModel->setStringList(glossary->terms(id,project->sourceLangCode())); //m_targetTermsModel->setStringList(glossary->terms(id,project->targetLangCode())); - m_reactOnSignals=true; + m_reactOnSignals = true; } void GlossaryWindow::currentChanged(int i) { Q_UNUSED(i); - m_reactOnSignals=false; + m_reactOnSignals = false; m_editor->show(); - m_reactOnSignals=true; + m_reactOnSignals = true; } void GlossaryWindow::showDefinitionForLang(int langModelIndex) { applyEntryChange(); - m_defLang=LanguageListModel::emptyLangInstance()->langCodeForSortModelRow(langModelIndex); + m_defLang = LanguageListModel::emptyLangInstance()->langCodeForSortModelRow(langModelIndex); m_definition->setPlainText(Project::instance()->glossary()->definition(m_id, m_defLang)); } void GlossaryWindow::applyEntryChange() { if (!m_reactOnSignals || !m_browser->currentIndex().isValid()) return; - QByteArray id=m_id;//modelIndexToId(m_browser->currentIndex()); + QByteArray id = m_id; //modelIndexToId(m_browser->currentIndex()); - Project* project=Project::instance(); - Glossary* glossary=project->glossary(); + Project* project = Project::instance(); + Glossary* glossary = project->glossary(); - if (m_subjectField->currentText()!=glossary->subjectField(id)) + if (m_subjectField->currentText() != glossary->subjectField(id)) glossary->setSubjectField(id, QString(), m_subjectField->currentText()); - if (m_definition->toPlainText()!=glossary->definition(id, m_defLang)) - glossary->setDefinition(id, m_defLang, m_definition->toPlainText()); + if (m_definition->toPlainText() != glossary->definition(id, m_defLang)) + glossary->setDefinition(id, m_defLang, m_definition->toPlainText()); //HACK to force finishing of the listview editing - QWidget* prevFocusWidget=QApplication::focusWidget(); + QWidget* prevFocusWidget = QApplication::focusWidget(); m_browser->setFocus(); if (prevFocusWidget) prevFocusWidget->setFocus(); // QSortFilterProxyModel* proxyModel=static_cast(model()); //GlossaryModel* sourceModel=static_cast(m_proxyModel->sourceModel()); - const QModelIndex& idx=m_proxyModel->mapToSource( m_browser->currentIndex() ); + const QModelIndex& idx = m_proxyModel->mapToSource(m_browser->currentIndex()); if (!idx.isValid()) return; //TODO display filename, optionally stripped like for filetab names - setCaption(i18nc("@title:window","Glossary"),!glossary->isClean()); + setCaption(i18nc("@title:window", "Glossary"), !glossary->isClean()); } void GlossaryWindow::selectEntry(const QByteArray& id) { //let it fetch the rows - QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents|QEventLoop::ExcludeSocketNotifiers|QEventLoop::WaitForMoreEvents, 100); + QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents | QEventLoop::ExcludeSocketNotifiers | QEventLoop::WaitForMoreEvents, 100); - QModelIndexList items=m_proxyModel->match(m_proxyModel->index(0,0),Qt::DisplayRole,QVariant(id),1,0); - if (items.count()) - { + QModelIndexList items = m_proxyModel->match(m_proxyModel->index(0, 0), Qt::DisplayRole, QVariant(id), 1, 0); + if (items.count()) { m_browser->setCurrentIndex(items.first()); - m_browser->scrollTo(items.first(),QAbstractItemView::PositionAtCenter); + m_browser->scrollTo(items.first(), QAbstractItemView::PositionAtCenter); //qCDebug(LOKALIZE_LOG)<setCurrentIndex(QModelIndex()); showEntryInEditor(id); @@ -465,10 +458,10 @@ void GlossaryWindow::newTermEntry(QString _english, QString _target) { - setCaption(i18nc("@title:window","Glossary"),true); + setCaption(i18nc("@title:window", "Glossary"), true); - GlossaryModel* sourceModel=static_cast(m_proxyModel->sourceModel()); - QByteArray id=sourceModel->appendRow(_english,_target); + GlossaryModel* sourceModel = static_cast(m_proxyModel->sourceModel()); + QByteArray id = sourceModel->appendRow(_english, _target); selectEntry(id); } @@ -480,32 +473,31 @@ void GlossaryWindow::rmTermEntry(int i) { - setCaption(i18nc("@title:window","Glossary"),true); + setCaption(i18nc("@title:window", "Glossary"), true); //QSortFilterProxyModel* proxyModel=static_cast(model()); - GlossaryModel* sourceModel=static_cast(m_proxyModel->sourceModel()); + GlossaryModel* sourceModel = static_cast(m_proxyModel->sourceModel()); - if (i==-1) - { + if (i == -1) { //NOTE actually we should remove selected items, not current one - const QModelIndex& current=m_browser->currentIndex(); + const QModelIndex& current = m_browser->currentIndex(); if (!current.isValid()) return; - i=m_proxyModel->mapToSource(current).row(); + i = m_proxyModel->mapToSource(current).row(); } sourceModel->removeRow(i); } void GlossaryWindow::restore() { - setCaption(i18nc("@title:window","Glossary"),false); + setCaption(i18nc("@title:window", "Glossary"), false); - Glossary* glossary=Project::instance()->glossary(); + Glossary* glossary = Project::instance()->glossary(); glossary->load(glossary->path()); - m_reactOnSignals=false; + m_reactOnSignals = false; showEntryInEditor(m_id); - m_reactOnSignals=true; + m_reactOnSignals = true; } bool GlossaryWindow::save() @@ -516,67 +508,66 @@ bool GlossaryWindow::queryClose() { - Glossary* glossary=Project::instance()->glossary(); + Glossary* glossary = Project::instance()->glossary(); applyEntryChange(); if (glossary->isClean()) return true; - switch(KMessageBox::warningYesNoCancel(this, - i18nc("@info","The glossary contains unsaved changes.\n\ -Do you want to save your changes or discard them?"),i18nc("@title:window","Warning"), - KStandardGuiItem::save(),KStandardGuiItem::discard())) - { - case KMessageBox::Yes: - return save(); - case KMessageBox::No: - restore(); - return true; - default: - return false; + switch (KMessageBox::warningYesNoCancel(this, + i18nc("@info", "The glossary contains unsaved changes.\n\ +Do you want to save your changes or discard them?"), i18nc("@title:window", "Warning"), + KStandardGuiItem::save(), KStandardGuiItem::discard())) { + case KMessageBox::Yes: + return save(); + case KMessageBox::No: + restore(); + return true; + default: + return false; } } //END GlossaryWindow void TermsListModel::setEntry(const QByteArray& id) { - m_id=id; - QStringList terms=m_glossary->terms(m_id,m_lang); + m_id = id; + QStringList terms = m_glossary->terms(m_id, m_lang); terms.append(QString()); //allow adding new terms setStringList(terms); } bool TermsListModel::setData(const QModelIndex& index, const QVariant& value, int role) { Q_UNUSED(role); - m_glossary->setTerm(m_id,m_lang,index.row(),value.toString()); + m_glossary->setTerm(m_id, m_lang, index.row(), value.toString()); setEntry(m_id); //allow adding new terms return true; } bool TermsListModel::removeRows(int row, int count, const QModelIndex& parent) { Q_UNUSED(count) - if (row==rowCount()-1) + if (row == rowCount() - 1) return false;// cannot delete non-existing item - m_glossary->rmTerm(m_id,m_lang,row); + m_glossary->rmTerm(m_id, m_lang, row); return QStringListModel::removeRows(row, 1, parent); } void TermListView::addTerm() { - setCurrentIndex(model()->index(model()->rowCount()-1, 0)); + setCurrentIndex(model()->index(model()->rowCount() - 1, 0)); edit(currentIndex()); } void TermListView::rmTerms() { - foreach(const QModelIndex& row, selectionModel()->selectedRows()) + foreach (const QModelIndex& row, selectionModel()->selectedRows()) model()->removeRow(row.row()); } diff --git a/src/glossary/tbxparser_obsolete.h b/src/glossary/tbxparser_obsolete.h --- a/src/glossary/tbxparser_obsolete.h +++ b/src/glossary/tbxparser_obsolete.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -28,7 +28,8 @@ #include "glossary.h" -namespace GlossaryNS { +namespace GlossaryNS +{ /** * loads only data we need to store in memory @@ -40,18 +41,16 @@ */ class TbxParser : public QXmlDefaultHandler { - enum State //localstate for getting chars into right place - { - null=0, + enum State { //localstate for getting chars into right place + null = 0, // termGrp, term, descripDefinition, descripSubjectField }; - enum Lang - { - langNull=0, + enum Lang { + langNull = 0, langEn, langTarget }; @@ -62,17 +61,17 @@ , m_glossary(glossary) {} - ~TbxParser(){} + ~TbxParser() {} bool startDocument(); - bool startElement(const QString&,const QString&,const QString&,const QXmlAttributes&); - bool endElement(const QString&,const QString&,const QString&); + bool startElement(const QString&, const QString&, const QString&, const QXmlAttributes&); + bool endElement(const QString&, const QString&, const QString&); bool characters(const QString&); private: // bool inTermTag:1; - State m_state:8; - Lang m_lang:8; + State m_state: 8; + Lang m_lang: 8; QString m_termEn; QString m_termOther; TermEntry m_entry; diff --git a/src/glossary/tbxparser_obsolete.cpp b/src/glossary/tbxparser_obsolete.cpp --- a/src/glossary/tbxparser_obsolete.cpp +++ b/src/glossary/tbxparser_obsolete.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -32,110 +32,91 @@ bool TbxParser::startDocument() { - m_state=null; - m_lang=langNull; + m_state = null; + m_lang = langNull; return true; } -bool TbxParser::startElement( const QString&, const QString&, - const QString& qName, - const QXmlAttributes& attr) +bool TbxParser::startElement(const QString&, const QString&, + const QString& qName, + const QXmlAttributes& attr) { - if (qName=="langSet") - { + if (qName == "langSet") { if (attr.value("xml:lang").startsWith("en")) - m_lang=langEn; - else if (attr.value("xml:lang")==Project::instance()->langCode()) - m_lang=langTarget; + m_lang = langEn; + else if (attr.value("xml:lang") == Project::instance()->langCode()) + m_lang = langTarget; else - m_lang=langNull; - } - else if (qName=="term") - { - m_state=term; - } - else if (qName=="termEntry") - { + m_lang = langNull; + } else if (qName == "term") { + m_state = term; + } else if (qName == "termEntry") { m_termEn.clear(); m_termOther.clear(); m_entry.clear(); - m_entry.id=attr.value("id"); - } - else if (qName=="descrip") - { - if (attr.value("type")=="definition") - m_state=descripDefinition; - else if (attr.value("type")=="subjectField") - m_state=descripSubjectField; + m_entry.id = attr.value("id"); + } else if (qName == "descrip") { + if (attr.value("type") == "definition") + m_state = descripDefinition; + else if (attr.value("type") == "subjectField") + m_state = descripSubjectField; } return true; } -bool TbxParser::endElement(const QString&,const QString&,const QString& qName) +bool TbxParser::endElement(const QString&, const QString&, const QString& qName) { - if (qName=="term") - { - if (m_lang==langEn) - { + if (qName == "term") { + if (m_lang == langEn) { m_entry.english << m_termEn; m_termEn.clear(); m_entry.english.last().squeeze(); - } - else if (m_lang==langTarget) - { + } else if (m_lang == langTarget) { m_entry.target << m_termOther; m_termOther.clear(); m_entry.target.last().squeeze(); } - } - else if (qName=="descrip") - { - if (m_state==descripSubjectField && !m_subjectField.isEmpty()) - { - m_entry.subjectField=Project::instance()->glossary()->subjectFields.indexOf(m_subjectField); - if (m_entry.subjectField==-1)//got this field value for the first time - { - m_entry.subjectField=Project::instance()->glossary()->subjectFields.size(); + } else if (qName == "descrip") { + if (m_state == descripSubjectField && !m_subjectField.isEmpty()) { + m_entry.subjectField = Project::instance()->glossary()->subjectFields.indexOf(m_subjectField); + if (m_entry.subjectField == -1) { //got this field value for the first time + m_entry.subjectField = Project::instance()->glossary()->subjectFields.size(); Project::instance()->glossary()->subjectFields << m_subjectField; } m_subjectField.clear(); } - } - else if (qName=="termEntry") - { + } else if (qName == "termEntry") { //sanity check --maybe this entry is only for another language? - if (m_entry.target.isEmpty()||m_entry.english.isEmpty()) + if (m_entry.target.isEmpty() || m_entry.english.isEmpty()) return true; - int index=m_glossary->termList.count(); + int index = m_glossary->termList.count(); m_glossary->termList.append(m_entry); m_glossary->hashTermEntry(index); m_entry.clear(); } - m_state=null; + m_state = null; return true; } -bool TbxParser::characters ( const QString & ch ) +bool TbxParser::characters(const QString & ch) { - if(m_state==term) - { - if (m_lang==langEn) - m_termEn+=ch.toLower();//this is important - else if (m_lang==langTarget) - m_termOther+=ch; - } - else if (m_state==descripDefinition) - m_entry.definition+=ch; - else if (m_state==descripSubjectField) - m_subjectField+=ch; + if (m_state == term) { + if (m_lang == langEn) + m_termEn += ch.toLower(); //this is important + else if (m_lang == langTarget) + m_termOther += ch; + } else if (m_state == descripDefinition) + m_entry.definition += ch; + else if (m_state == descripSubjectField) + m_subjectField += ch; return true; diff --git a/src/lokalizemainwindow.h b/src/lokalizemainwindow.h --- a/src/lokalizemainwindow.h +++ b/src/lokalizemainwindow.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -43,7 +43,10 @@ class MultiEditorAdaptor; class ProjectScriptingPlugin; class FileSearchTab; -namespace TM {class TMTab;} +namespace TM +{ +class TMTab; +} /** * @short Lokalize MDI (tabbed) window. @@ -85,8 +88,14 @@ void editorClosed(QObject* obj); void resetMultiEditorAdaptor(); - void openProject(const QUrl& url){openProject(url.toLocalFile());}//convenience overload for recent projects action - void openProject(){openProject(QString());} + void openProject(const QUrl& url) + { + openProject(url.toLocalFile()); //convenience overload for recent projects action + } + void openProject() + { + openProject(QString()); + } public slots: @@ -108,7 +117,7 @@ /// @returns 0 if current tab is not of Editor type Q_SCRIPTABLE QObject* activeEditor(); - + /// @returns editor with @param path loaded or 0 if there is no such editor. Q_SCRIPTABLE QObject* editorForFile(const QString& path); /** @@ -128,12 +137,15 @@ //returns 0 if error EditorTab* fileOpen_(QString url); - EditorTab* fileOpen(QString url=QString(),int entry=0, bool setAsActive=true, const QString& mergeFile=QString(), bool silent=false); + EditorTab* fileOpen(QString url = QString(), int entry = 0, bool setAsActive = true, const QString& mergeFile = QString(), bool silent = false); EditorTab* fileOpen(const QString& url, const QString& source, const QString& ctxt); EditorTab* fileOpen(const QString& url, DocPosition docPos, int selection); - EditorTab* fileOpen(const QUrl& url){return fileOpen(url.toLocalFile());} + EditorTab* fileOpen(const QUrl& url) + { + return fileOpen(url.toLocalFile()); + } TM::TMTab* showTM(); - FileSearchTab* showFileSearch(bool activate=true); + FileSearchTab* showFileSearch(bool activate = true); void fileSearchNext(); void addFilesToSearch(const QStringList&); @@ -174,20 +186,20 @@ class ProjectScriptingPlugin: public Kross::ScriptingPlugin { -Q_OBJECT + Q_OBJECT public: ProjectScriptingPlugin(QObject* lokalize, QObject* editor); ~ProjectScriptingPlugin(); - void setDOMDocument (const QDomDocument &document, bool merge = false); + void setDOMDocument(const QDomDocument &document, bool merge = false); private slots: void doAutoruns(); }; class DelayedFileOpener: public QObject { -Q_OBJECT + Q_OBJECT public: DelayedFileOpener(const QVector& urls, LokalizeMainWindow* lmw); diff --git a/src/lokalizemainwindow.cpp b/src/lokalizemainwindow.cpp --- a/src/lokalizemainwindow.cpp +++ b/src/lokalizemainwindow.cpp @@ -68,16 +68,16 @@ LokalizeMainWindow::LokalizeMainWindow() - : KXmlGuiWindow() - , m_mdiArea(new QMdiArea) - , m_prevSubWindow(0) - , m_projectSubWindow(0) - , m_translationMemorySubWindow(0) - , m_editorActions(new QActionGroup(this)) - , m_managerActions(new QActionGroup(this)) - , m_spareEditor(new EditorTab(this,false)) - , m_multiEditorAdaptor(new MultiEditorAdaptor(m_spareEditor)) - , m_projectScriptingPlugin(0) + : KXmlGuiWindow() + , m_mdiArea(new QMdiArea) + , m_prevSubWindow(0) + , m_projectSubWindow(0) + , m_translationMemorySubWindow(0) + , m_editorActions(new QActionGroup(this)) + , m_managerActions(new QActionGroup(this)) + , m_spareEditor(new EditorTab(this, false)) + , m_multiEditorAdaptor(new MultiEditorAdaptor(m_spareEditor)) + , m_projectScriptingPlugin(0) { m_spareEditor->hide(); m_mdiArea->setViewMode(QMdiArea::TabbedView); @@ -87,31 +87,29 @@ m_mdiArea->setTabsClosable(true); setCentralWidget(m_mdiArea); - connect(m_mdiArea, &QMdiArea::subWindowActivated,this,&LokalizeMainWindow::slotSubWindowActivated); + connect(m_mdiArea, &QMdiArea::subWindowActivated, this, &LokalizeMainWindow::slotSubWindowActivated); setupActions(); //prevent relayout of dockwidgets - m_mdiArea->setOption(QMdiArea::DontMaximizeSubWindowOnActivation,true); + m_mdiArea->setOption(QMdiArea::DontMaximizeSubWindowOnActivation, true); connect(Project::instance(), QOverload::of(&Project::fileOpenRequested), this, QOverload::of(&LokalizeMainWindow::fileOpen_), Qt::QueuedConnection); connect(Project::instance(), &Project::configChanged, this, &LokalizeMainWindow::projectSettingsChanged); connect(Project::instance(), &Project::closed, this, &LokalizeMainWindow::closeProject); showProjectOverview(); showTranslationMemory(); //fix for #342558 - for (int i=ID_STATUS_CURRENT;i<=ID_STATUS_ISFUZZY;i++) - { + for (int i = ID_STATUS_CURRENT; i <= ID_STATUS_ISFUZZY; i++) { m_statusBarLabels.append(new QLabel()); statusBar()->insertWidget(i, m_statusBarLabels.last(), 2); } - setAttribute(Qt::WA_DeleteOnClose,true); + setAttribute(Qt::WA_DeleteOnClose, true); - if (!qApp->isSessionRestored()) - { + if (!qApp->isSessionRestored()) { KConfig config; - KConfigGroup stateGroup(&config,"State"); + KConfigGroup stateGroup(&config, "State"); readProperties(stateGroup); } @@ -121,13 +119,12 @@ } void LokalizeMainWindow::initLater() { - if(!m_prevSubWindow && m_projectSubWindow) + if (!m_prevSubWindow && m_projectSubWindow) slotSubWindowActivated(m_projectSubWindow); - if(!Project::instance()->isTmSupported()) - { - KNotification* notification=new KNotification("NoSqlModulesAvailable", this); - notification->setText( i18nc("@info","No Qt Sql modules were found. Translation memory will not work.") ); + if (!Project::instance()->isTmSupported()) { + KNotification* notification = new KNotification("NoSqlModulesAvailable", this); + notification->setText(i18nc("@info", "No Qt Sql modules were found. Translation memory will not work.")); notification->sendEvent(); } } @@ -137,126 +134,118 @@ TM::cancelAllJobs(); KConfig config; - KConfigGroup stateGroup(&config,"State"); + KConfigGroup stateGroup(&config, "State"); saveProjectState(stateGroup); m_multiEditorAdaptor->deleteLater(); //Disconnect the signals pointing to this MainWindow object QList::iterator sw; - for (sw = m_fileToEditor.values().begin(); sw != m_fileToEditor.values().end(); ++sw) - { + for (sw = m_fileToEditor.values().begin(); sw != m_fileToEditor.values().end(); ++sw) { disconnect(*sw, &QMdiSubWindow::destroyed, this, &LokalizeMainWindow::editorClosed); EditorTab* w = static_cast((*sw)->widget()); disconnect(w, &EditorTab::aboutToBeClosed, this, &LokalizeMainWindow::resetMultiEditorAdaptor); disconnect(w, QOverload::of(&EditorTab::fileOpenRequested), this, QOverload::of(&LokalizeMainWindow::fileOpen)); - disconnect(w, QOverload::of(&EditorTab::tmLookupRequested), this, QOverload::of(&LokalizeMainWindow::lookupInTranslationMemory)); + disconnect(w, QOverload::of(&EditorTab::tmLookupRequested), this, QOverload::of(&LokalizeMainWindow::lookupInTranslationMemory)); } - qCWarning(LOKALIZE_LOG)<<"MainWindow destroyed"; + qCWarning(LOKALIZE_LOG) << "MainWindow destroyed"; } void LokalizeMainWindow::slotSubWindowActivated(QMdiSubWindow* w) { //QTime aaa;aaa.start(); - if (!w || m_prevSubWindow==w) + if (!w || m_prevSubWindow == w) return; w->setUpdatesEnabled(true); //QTBUG-23289 - if (m_prevSubWindow) - { + if (m_prevSubWindow) { m_prevSubWindow->setUpdatesEnabled(false); - LokalizeSubwindowBase* prevEditor=static_cast( m_prevSubWindow->widget() ); + LokalizeSubwindowBase* prevEditor = static_cast(m_prevSubWindow->widget()); prevEditor->hideDocks(); - guiFactory()->removeClient( prevEditor->guiClient() ); + guiFactory()->removeClient(prevEditor->guiClient()); prevEditor->statusBarItems.unregisterStatusBar(); - if (qobject_cast(prevEditor)) - { - EditorTab* w=static_cast( prevEditor ); - EditorState state=w->state(); - m_lastEditorState=state.dockWidgets.toBase64(); - } - /* - - QMenu* projectActions=static_cast(factory()->container("project_actions",this)); - QList actionz=projectActions->actions(); - - int i=actionz.size(); - //projectActions->menuAction()->setVisible(i); - //qCWarning(LOKALIZE_LOG)<<"adding object"<=0) - { - disconnect(w, SIGNAL(signalNewEntryDisplayed()),actionz.at(i),SLOT(signalNewEntryDisplayed())); - //static_cast(actionz.at(i))->addObject(static_cast( editor )->adaptor(),"Editor",Kross::ChildrenInterface::AutoConnectSignals); - //static_cast(actionz.at(i))->trigger(); - } + if (qobject_cast(prevEditor)) { + EditorTab* w = static_cast(prevEditor); + EditorState state = w->state(); + m_lastEditorState = state.dockWidgets.toBase64(); } -*/ - } - LokalizeSubwindowBase* editor=static_cast( w->widget() ); - if (qobject_cast(editor)) - { - EditorTab* w=static_cast( editor ); - w->setProperFocus(); + /* - EditorState state=w->state(); - m_lastEditorState=state.dockWidgets.toBase64(); - - m_multiEditorAdaptor->setEditorTab(w); -// connect(m_multiEditorAdaptor,SIGNAL(srcFileOpenRequested(QString,int)),this,SLOT(showTM())); -/* QMenu* projectActions=static_cast(factory()->container("project_actions",this)); QList actionz=projectActions->actions(); int i=actionz.size(); //projectActions->menuAction()->setVisible(i); //qCWarning(LOKALIZE_LOG)<<"adding object"<=0) { - connect(w, SIGNAL(signalNewEntryDisplayed()),actionz.at(i),SLOT(signalNewEntryDisplayed())); + disconnect(w, SIGNAL(signalNewEntryDisplayed()),actionz.at(i),SLOT(signalNewEntryDisplayed())); //static_cast(actionz.at(i))->addObject(static_cast( editor )->adaptor(),"Editor",Kross::ChildrenInterface::AutoConnectSignals); //static_cast(actionz.at(i))->trigger(); - }*/ + } + } + */ + } + LokalizeSubwindowBase* editor = static_cast(w->widget()); + if (qobject_cast(editor)) { + EditorTab* w = static_cast(editor); + w->setProperFocus(); + + EditorState state = w->state(); + m_lastEditorState = state.dockWidgets.toBase64(); + + m_multiEditorAdaptor->setEditorTab(w); +// connect(m_multiEditorAdaptor,SIGNAL(srcFileOpenRequested(QString,int)),this,SLOT(showTM())); + /* + QMenu* projectActions=static_cast(factory()->container("project_actions",this)); + QList actionz=projectActions->actions(); + + int i=actionz.size(); + //projectActions->menuAction()->setVisible(i); + //qCWarning(LOKALIZE_LOG)<<"adding object"<=0) + { + connect(w, SIGNAL(signalNewEntryDisplayed()),actionz.at(i),SLOT(signalNewEntryDisplayed())); + //static_cast(actionz.at(i))->addObject(static_cast( editor )->adaptor(),"Editor",Kross::ChildrenInterface::AutoConnectSignals); + //static_cast(actionz.at(i))->trigger(); + }*/ QTabBar* tw = m_mdiArea->findChild(); - if(tw) tw->setTabToolTip(tw->currentIndex(), w->currentFilePath()); + if (tw) tw->setTabToolTip(tw->currentIndex(), w->currentFilePath()); emit editorActivated(); - } - else if (w==m_projectSubWindow && m_projectSubWindow) - { + } else if (w == m_projectSubWindow && m_projectSubWindow) { QTabBar* tw = m_mdiArea->findChild(); - if(tw) tw->setTabToolTip(tw->currentIndex(), Project::instance()->path()); + if (tw) tw->setTabToolTip(tw->currentIndex(), Project::instance()->path()); } editor->showDocks(); editor->statusBarItems.registerStatusBar(statusBar(), m_statusBarLabels); - guiFactory()->addClient( editor->guiClient() ); + guiFactory()->addClient(editor->guiClient()); - m_prevSubWindow=w; + m_prevSubWindow = w; //qCWarning(LOKALIZE_LOG)<<"finished"< editors=m_mdiArea->subWindowList(); - int i=editors.size(); - while (--i>=0) - { + QList editors = m_mdiArea->subWindowList(); + int i = editors.size(); + while (--i >= 0) { //if (editors.at(i)==m_projectSubWindow) if (!qobject_cast(editors.at(i)->widget())) continue; - if (!static_cast( editors.at(i)->widget() )->queryClose()) + if (!static_cast(editors.at(i)->widget())->queryClose()) return false; } - bool ok=Project::instance()->queryCloseForAuxiliaryWindows(); - - if (ok) - { + bool ok = Project::instance()->queryCloseForAuxiliaryWindows(); + + if (ok) { QThreadPool::globalInstance()->clear(); Project::instance()->model()->threadPool()->clear(); } @@ -268,39 +257,33 @@ } EditorTab* LokalizeMainWindow::fileOpen(QString filePath, int entry, bool setAsActive, const QString& mergeFile, bool silent) { - if (filePath.length()) - { - FileToEditor::const_iterator it=m_fileToEditor.constFind(filePath); - if (it!=m_fileToEditor.constEnd()) - { - qCWarning(LOKALIZE_LOG)<<"already opened:"<setActiveSubWindow(sw); return static_cast(sw->widget()); } } } QByteArray state = m_lastEditorState; EditorTab* w = new EditorTab(this); - QMdiSubWindow* sw=0; + QMdiSubWindow* sw = 0; //create QMdiSubWindow BEFORE fileOpen() because it causes some strange QMdiArea behaviour otherwise if (filePath.length()) sw = m_mdiArea->addSubWindow(w); QString suggestedDirPath; - QMdiSubWindow* activeSW=m_mdiArea->currentSubWindow(); - if (activeSW && qobject_cast(activeSW->widget())) - { - QString fp=static_cast(activeSW->widget())->currentFilePath(); - if (fp.length()) suggestedDirPath=QFileInfo(fp).absolutePath(); + QMdiSubWindow* activeSW = m_mdiArea->currentSubWindow(); + if (activeSW && qobject_cast(activeSW->widget())) { + QString fp = static_cast(activeSW->widget())->currentFilePath(); + if (fp.length()) suggestedDirPath = QFileInfo(fp).absolutePath(); } - if (!w->fileOpen(filePath,suggestedDirPath,silent)) - { - if (sw) - { + if (!w->fileOpen(filePath, suggestedDirPath, silent)) { + if (sw) { m_mdiArea->removeSubWindow(sw); sw->deleteLater(); } @@ -318,12 +301,10 @@ if (entry/* || offset*/) w->gotoEntry(DocPosition(entry/*, DocPosition::Target, 0, offset*/)); - if (setAsActive) - { + if (setAsActive) { m_toBeActiveSubWindow = sw; QTimer::singleShot(0, this, &LokalizeMainWindow::applyToBeActiveSubWindow); - } - else + } else sw->setUpdatesEnabled(false); //QTBUG-23289 if (!mergeFile.isEmpty()) @@ -336,20 +317,18 @@ connect(w, QOverload::of(&EditorTab::tmLookupRequested), this, QOverload::of(&LokalizeMainWindow::lookupInTranslationMemory)); filePath = w->currentFilePath(); - QStringRef fnSlashed=filePath.midRef(filePath.lastIndexOf('/')); + QStringRef fnSlashed = filePath.midRef(filePath.lastIndexOf('/')); FileToEditor::const_iterator i = m_fileToEditor.constBegin(); - while (i != m_fileToEditor.constEnd()) - { - if (i.key().endsWith(fnSlashed)) - { + while (i != m_fileToEditor.constEnd()) { + if (i.key().endsWith(fnSlashed)) { static_cast(i.value()->widget())->setFullPathShown(true); w->setFullPathShown(true); } ++i; } - m_fileToEditor.insert(filePath,sw); + m_fileToEditor.insert(filePath, sw); - sw->setAttribute(Qt::WA_DeleteOnClose,true); + sw->setAttribute(Qt::WA_DeleteOnClose, true); emit editorAdded(); return w; } @@ -366,35 +345,34 @@ EditorTab* LokalizeMainWindow::fileOpen(const QString& filePath, const QString& source, const QString& ctxt) { - EditorTab* w=fileOpen(filePath, 0, true); + EditorTab* w = fileOpen(filePath, 0, true); if (!w) return 0;//TODO message - w->findEntryBySourceContext(source,ctxt); + w->findEntryBySourceContext(source, ctxt); return w; } EditorTab* LokalizeMainWindow::fileOpen(const QString& filePath, DocPosition docPos, int selection) { - EditorTab* w=fileOpen(filePath, 0, true); + EditorTab* w = fileOpen(filePath, 0, true); if (!w) return 0;//TODO message w->gotoEntry(docPos, selection); return w; } QObject* LokalizeMainWindow::projectOverview() { - if (!m_projectSubWindow) - { - ProjectTab* w=new ProjectTab(this); - m_projectSubWindow=m_mdiArea->addSubWindow(w); + if (!m_projectSubWindow) { + ProjectTab* w = new ProjectTab(this); + m_projectSubWindow = m_mdiArea->addSubWindow(w); w->showMaximized(); m_projectSubWindow->showMaximized(); connect(w, QOverload::of(&ProjectTab::fileOpenRequested), this, QOverload::of(&LokalizeMainWindow::fileOpen_)); connect(w, QOverload::of(&ProjectTab::projectOpenRequested), this, QOverload::of(&LokalizeMainWindow::openProject)); connect(w, QOverload<>::of(&ProjectTab::projectOpenRequested), this, QOverload<>::of(&LokalizeMainWindow::openProject)); connect(w, QOverload::of(&ProjectTab::searchRequested), this, QOverload::of(&LokalizeMainWindow::addFilesToSearch)); } - if (m_mdiArea->currentSubWindow()==m_projectSubWindow) + if (m_mdiArea->currentSubWindow() == m_projectSubWindow) return m_projectSubWindow->widget(); return 0; } @@ -407,16 +385,14 @@ TM::TMTab* LokalizeMainWindow::showTM() { - if (!Project::instance()->isTmSupported()) - { + if (!Project::instance()->isTmSupported()) { KMessageBox::information(0, i18n("TM facility requires SQLite Qt module."), i18n("No SQLite module available")); return 0; } - if (!m_translationMemorySubWindow) - { - TM::TMTab* w=new TM::TMTab(this); - m_translationMemorySubWindow=m_mdiArea->addSubWindow(w); + if (!m_translationMemorySubWindow) { + TM::TMTab* w = new TM::TMTab(this); + m_translationMemorySubWindow = m_mdiArea->addSubWindow(w); w->showMaximized(); m_translationMemorySubWindow->showMaximized(); connect(w, QOverload::of(&TM::TMTab::fileOpenRequested), this, QOverload::of(&LokalizeMainWindow::fileOpen)); @@ -428,23 +404,20 @@ FileSearchTab* LokalizeMainWindow::showFileSearch(bool activate) { - EditorTab* precedingEditor=qobject_cast(activeEditor()); + EditorTab* precedingEditor = qobject_cast(activeEditor()); - if (!m_fileSearchSubWindow) - { - FileSearchTab* w=new FileSearchTab(this); - m_fileSearchSubWindow=m_mdiArea->addSubWindow(w); + if (!m_fileSearchSubWindow) { + FileSearchTab* w = new FileSearchTab(this); + m_fileSearchSubWindow = m_mdiArea->addSubWindow(w); w->showMaximized(); m_fileSearchSubWindow->showMaximized(); connect(w, QOverload::of(&FileSearchTab::fileOpenRequested), this, QOverload::of(&LokalizeMainWindow::fileOpen)); connect(w, QOverload::of(&FileSearchTab::fileOpenRequested), this, QOverload::of(&LokalizeMainWindow::fileOpen_)); } - if (activate) - { + if (activate) { m_mdiArea->setActiveSubWindow(m_fileSearchSubWindow); - if (precedingEditor) - { + if (precedingEditor) { if (precedingEditor->selectionInSource().length()) static_cast(m_fileSearchSubWindow->widget())->setSourceQuery(precedingEditor->selectionInSource()); if (precedingEditor->selectionInTarget().length()) @@ -456,14 +429,14 @@ void LokalizeMainWindow::fileSearchNext() { - FileSearchTab* w=showFileSearch(/*activate=*/false); + FileSearchTab* w = showFileSearch(/*activate=*/false); //TODO fill search params based on current selection w->fileSearchNext(); } void LokalizeMainWindow::addFilesToSearch(const QStringList& files) { - FileSearchTab* w=showFileSearch(); + FileSearchTab* w = showFileSearch(); w->addFilesToSearch(files); } @@ -479,32 +452,32 @@ //all operations that can be done after initial setup //(via QTimer::singleShot) go to initLater() - QTime aaa;aaa.start(); + QTime aaa; aaa.start(); setStandardToolBarMenuEnabled(true); QAction *action; - KActionCollection* ac=actionCollection(); + KActionCollection* ac = actionCollection(); KActionCategory* actionCategory; - KActionCategory* file=new KActionCategory(i18nc("@title actions category","File"), ac); + KActionCategory* file = new KActionCategory(i18nc("@title actions category", "File"), ac); //KActionCategory* config=new KActionCategory(i18nc("@title actions category","Configuration"), ac); - KActionCategory* glossary=new KActionCategory(i18nc("@title actions category","Glossary"), ac); - KActionCategory* tm=new KActionCategory(i18nc("@title actions category","Translation Memory"), ac); - KActionCategory* proj=new KActionCategory(i18nc("@title actions category","Project"), ac); + KActionCategory* glossary = new KActionCategory(i18nc("@title actions category", "Glossary"), ac); + KActionCategory* tm = new KActionCategory(i18nc("@title actions category", "Translation Memory"), ac); + KActionCategory* proj = new KActionCategory(i18nc("@title actions category", "Project"), ac); - actionCategory=file; + actionCategory = file; // File //KStandardAction::open(this, SLOT(fileOpen()), ac); - file->addAction(KStandardAction::Open,this, SLOT(fileOpen())); - m_openRecentFileAction = KStandardAction::openRecent(this,SLOT(fileOpen(QUrl)),ac); + file->addAction(KStandardAction::Open, this, SLOT(fileOpen())); + m_openRecentFileAction = KStandardAction::openRecent(this, SLOT(fileOpen(QUrl)), ac); file->addAction(KStandardAction::Quit, qApp, SLOT(closeAllWindows())); //Settings - SettingsController* sc=SettingsController::instance(); - KStandardAction::preferences(sc, SLOT(showSettingsDialog()),ac); + SettingsController* sc = SettingsController::instance(); + KStandardAction::preferences(sc, SLOT(showSettingsDialog()), ac); #define ADD_ACTION_SHORTCUT(_name,_text,_shortcut)\ action = actionCategory->addAction(QStringLiteral(_name));\ @@ -516,62 +489,62 @@ //documentBack //KStandardAction::close(m_mdiArea, SLOT(closeActiveSubWindow()), ac); - actionCategory=file; - ADD_ACTION_SHORTCUT("next-tab",i18n("Next tab"),Qt::CTRL+Qt::Key_BracketRight) + actionCategory = file; + ADD_ACTION_SHORTCUT("next-tab", i18n("Next tab"), Qt::CTRL + Qt::Key_BracketRight) connect(action, &QAction::triggered, m_mdiArea, &QMdiArea::activateNextSubWindow); - ADD_ACTION_SHORTCUT("prev-tab",i18n("Previous tab"),Qt::CTRL+Qt::Key_BracketLeft) + ADD_ACTION_SHORTCUT("prev-tab", i18n("Previous tab"), Qt::CTRL + Qt::Key_BracketLeft) connect(action, &QAction::triggered, m_mdiArea, &QMdiArea::activatePreviousSubWindow); //Tools - actionCategory=glossary; - Project* project=Project::instance(); - ADD_ACTION_SHORTCUT("tools_glossary",i18nc("@action:inmenu","Glossary"),Qt::CTRL+Qt::ALT+Qt::Key_G) + actionCategory = glossary; + Project* project = Project::instance(); + ADD_ACTION_SHORTCUT("tools_glossary", i18nc("@action:inmenu", "Glossary"), Qt::CTRL + Qt::ALT + Qt::Key_G) connect(action, &QAction::triggered, project, &Project::showGlossary); - actionCategory=tm; - ADD_ACTION_SHORTCUT("tools_tm",i18nc("@action:inmenu","Translation memory"),Qt::Key_F7) + actionCategory = tm; + ADD_ACTION_SHORTCUT("tools_tm", i18nc("@action:inmenu", "Translation memory"), Qt::Key_F7) connect(action, &QAction::triggered, this, &LokalizeMainWindow::showTM); - action = tm->addAction("tools_tm_manage",project,SLOT(showTMManager())); - action->setText(i18nc("@action:inmenu","Manage translation memories")); + action = tm->addAction("tools_tm_manage", project, SLOT(showTMManager())); + action->setText(i18nc("@action:inmenu", "Manage translation memories")); //Project - actionCategory=proj; - ADD_ACTION_SHORTCUT("project_overview",i18nc("@action:inmenu","Project overview"),Qt::Key_F4) + actionCategory = proj; + ADD_ACTION_SHORTCUT("project_overview", i18nc("@action:inmenu", "Project overview"), Qt::Key_F4) connect(action, &QAction::triggered, this, &LokalizeMainWindow::showProjectOverview); - action = proj->addAction(QStringLiteral("project_configure"),sc,SLOT(projectConfigure())); - action->setText(i18nc("@action:inmenu","Configure project...")); + action = proj->addAction(QStringLiteral("project_configure"), sc, SLOT(projectConfigure())); + action->setText(i18nc("@action:inmenu", "Configure project...")); - action = proj->addAction(QStringLiteral("project_create"),sc,SLOT(projectCreate())); - action->setText(i18nc("@action:inmenu","Create software translation project...")); + action = proj->addAction(QStringLiteral("project_create"), sc, SLOT(projectCreate())); + action->setText(i18nc("@action:inmenu", "Create software translation project...")); - action = proj->addAction(QStringLiteral("project_create_odf"),Project::instance(), SLOT(projectOdfCreate())); - action->setText(i18nc("@action:inmenu","Create OpenDocument translation project...")); + action = proj->addAction(QStringLiteral("project_create_odf"), Project::instance(), SLOT(projectOdfCreate())); + action->setText(i18nc("@action:inmenu", "Create OpenDocument translation project...")); - action = proj->addAction(QStringLiteral("project_open"),this,SLOT(openProject())); - action->setText(i18nc("@action:inmenu","Open project...")); + action = proj->addAction(QStringLiteral("project_open"), this, SLOT(openProject())); + action->setText(i18nc("@action:inmenu", "Open project...")); action->setIcon(QIcon::fromTheme("project-open")); - m_openRecentProjectAction=new KRecentFilesAction(i18nc("@action:inmenu","Open recent project"),this); - action = proj->addAction(QStringLiteral("project_open_recent"),m_openRecentProjectAction); + m_openRecentProjectAction = new KRecentFilesAction(i18nc("@action:inmenu", "Open recent project"), this); + action = proj->addAction(QStringLiteral("project_open_recent"), m_openRecentProjectAction); connect(m_openRecentProjectAction, QOverload::of(&KRecentFilesAction::urlSelected), this, QOverload::of(&LokalizeMainWindow::openProject)); //Qt::QueuedConnection: defer until event loop is running to eliminate QWidgetPrivate::showChildren(bool) startup crash connect(Project::instance(), &Project::loaded, this, &LokalizeMainWindow::projectLoaded, Qt::QueuedConnection); - ADD_ACTION_SHORTCUT("tools_filesearch",i18nc("@action:inmenu","Search and replace in files"),Qt::Key_F6) + ADD_ACTION_SHORTCUT("tools_filesearch", i18nc("@action:inmenu", "Search and replace in files"), Qt::Key_F6) connect(action, &QAction::triggered, this, &LokalizeMainWindow::showFileSearch); - ADD_ACTION_SHORTCUT("tools_filesearch_next",i18nc("@action:inmenu","Find next in files"),Qt::META+Qt::Key_F3) + ADD_ACTION_SHORTCUT("tools_filesearch_next", i18nc("@action:inmenu", "Find next in files"), Qt::META + Qt::Key_F3) connect(action, &QAction::triggered, this, &LokalizeMainWindow::fileSearchNext); - action = ac->addAction(QStringLiteral("tools_widgettextcapture"),this,SLOT(widgetTextCapture())); - action->setText(i18nc("@action:inmenu","Widget text capture")); + action = ac->addAction(QStringLiteral("tools_widgettextcapture"), this, SLOT(widgetTextCapture())); + action->setText(i18nc("@action:inmenu", "Widget text capture")); - setupGUI(Default,QStringLiteral("lokalizemainwindowui.rc")); + setupGUI(Default, QStringLiteral("lokalizemainwindowui.rc")); //qCDebug(LOKALIZE_LOG)<<"action setup finished"<subWindowList()) - { - if (subwindow==m_translationMemorySubWindow && m_translationMemorySubWindow) + foreach (QMdiSubWindow* subwindow, m_mdiArea->subWindowList()) { + if (subwindow == m_translationMemorySubWindow && m_translationMemorySubWindow) subwindow->deleteLater(); - else if (qobject_cast(subwindow->widget())) - { + else if (qobject_cast(subwindow->widget())) { m_fileToEditor.remove(static_cast(subwindow->widget())->currentFilePath());//safety m_mdiArea->removeSubWindow(subwindow); subwindow->deleteLater(); @@ -602,7 +573,7 @@ void LokalizeMainWindow::openProject(QString path) { - path=SettingsController::instance()->projectOpen(path, false);//dry run + path = SettingsController::instance()->projectOpen(path, false); //dry run if (path.isEmpty()) return; @@ -618,24 +589,23 @@ void LokalizeMainWindow::saveProjectState(KConfigGroup& stateGroup) { - QList editors=m_mdiArea->subWindowList(); - + QList editors = m_mdiArea->subWindowList(); + QStringList files; QStringList mergeFiles; QList dockWidgets; //QList offsets; QList entries; - QMdiSubWindow* activeSW=m_mdiArea->currentSubWindow(); - int activeSWIndex=-1; - int i=editors.size(); - while (--i>=0) - { + QMdiSubWindow* activeSW = m_mdiArea->currentSubWindow(); + int activeSWIndex = -1; + int i = editors.size(); + while (--i >= 0) { //if (editors.at(i)==m_projectSubWindow) if (!editors.at(i) || !qobject_cast(editors.at(i)->widget())) continue; - if (editors.at(i)==activeSW) - activeSWIndex=files.size(); - EditorState state=static_cast( editors.at(i)->widget() )->state(); + if (editors.at(i) == activeSW) + activeSWIndex = files.size(); + EditorState state = static_cast(editors.at(i)->widget())->state(); files.append(state.filePath); mergeFiles.append(state.mergeFilePath); dockWidgets.append(state.dockWidgets.toBase64()); @@ -649,115 +619,108 @@ dockWidgets.append(m_lastEditorState); // save last state if no editor open if (stateGroup.isValid()) - stateGroup.writeEntry("Project",Project::instance()->path()); + stateGroup.writeEntry("Project", Project::instance()->path()); KConfig config; - KConfigGroup projectStateGroup(&config,"State-"+Project::instance()->path()); - projectStateGroup.writeEntry("Active",activeSWIndex); - projectStateGroup.writeEntry("Files",files); - projectStateGroup.writeEntry("MergeFiles",mergeFiles); - projectStateGroup.writeEntry("DockWidgets",dockWidgets); + KConfigGroup projectStateGroup(&config, "State-" + Project::instance()->path()); + projectStateGroup.writeEntry("Active", activeSWIndex); + projectStateGroup.writeEntry("Files", files); + projectStateGroup.writeEntry("MergeFiles", mergeFiles); + projectStateGroup.writeEntry("DockWidgets", dockWidgets); //stateGroup.writeEntry("Offsets",offsets); - projectStateGroup.writeEntry("Entries",entries); - if (m_projectSubWindow) - { + projectStateGroup.writeEntry("Entries", entries); + if (m_projectSubWindow) { ProjectTab *w = static_cast(m_projectSubWindow->widget()); - if (w->unitsCount()>0) + if (w->unitsCount() > 0) projectStateGroup.writeEntry("UnitsCount", w->unitsCount()); } - QString nameSpecifier=Project::instance()->path(); + QString nameSpecifier = Project::instance()->path(); if (!nameSpecifier.isEmpty()) nameSpecifier.prepend('-'); - KConfig* c=stateGroup.isValid()?stateGroup.config():&config; - m_openRecentFileAction->saveEntries(KConfigGroup(c,"RecentFiles"+nameSpecifier)); + KConfig* c = stateGroup.isValid() ? stateGroup.config() : &config; + m_openRecentFileAction->saveEntries(KConfigGroup(c, "RecentFiles" + nameSpecifier)); - m_openRecentProjectAction->saveEntries(KConfigGroup(&config,"RecentProjects")); + m_openRecentProjectAction->saveEntries(KConfigGroup(&config, "RecentProjects")); } void LokalizeMainWindow::readProperties(const KConfigGroup& stateGroup) { KConfig config; - const KConfig* c=stateGroup.isValid()?stateGroup.config():&config; - m_openRecentProjectAction->loadEntries(KConfigGroup(c,"RecentProjects")); + const KConfig* c = stateGroup.isValid() ? stateGroup.config() : &config; + m_openRecentProjectAction->loadEntries(KConfigGroup(c, "RecentProjects")); - QString path=stateGroup.readEntry("Project",QString()); - if (Project::instance()->isLoaded() || path.isEmpty()) - { + QString path = stateGroup.readEntry("Project", QString()); + if (Project::instance()->isLoaded() || path.isEmpty()) { //1. we weren't existing yet when the signal was emitted //2. defer until event loop is running to eliminate QWidgetPrivate::showChildren(bool) startup crash QTimer::singleShot(0, this, &LokalizeMainWindow::projectLoaded); - } - else + } else Project::instance()->load(path); } void LokalizeMainWindow::projectLoaded() { - QString projectPath=Project::instance()->path(); - qCDebug(LOKALIZE_LOG)<addUrl( QUrl::fromLocalFile(projectPath) ); + QString projectPath = Project::instance()->path(); + qCDebug(LOKALIZE_LOG) << projectPath; + m_openRecentProjectAction->addUrl(QUrl::fromLocalFile(projectPath)); KConfig config; - QString nameSpecifier=projectPath; + QString nameSpecifier = projectPath; if (!nameSpecifier.isEmpty()) nameSpecifier.prepend('-'); - m_openRecentFileAction->loadEntries(KConfigGroup(&config,"RecentFiles"+nameSpecifier)); + m_openRecentFileAction->loadEntries(KConfigGroup(&config, "RecentFiles" + nameSpecifier)); //if project isn't loaded, still restore opened files from "State-" - KConfigGroup projectStateGroup(&config,"State-"+projectPath); + KConfigGroup projectStateGroup(&config, "State-" + projectPath); QStringList files; QStringList mergeFiles; QList dockWidgets; //QList offsets; QList entries; projectOverview(); - if (m_projectSubWindow) - { + if (m_projectSubWindow) { ProjectTab *w = static_cast(m_projectSubWindow->widget()); w->setLegacyUnitsCount(projectStateGroup.readEntry("UnitsCount", 0)); QTabBar* tw = m_mdiArea->findChild(); - if(tw) for(int i=0;icount();i++) - if (tw->tabText(i)==w->windowTitle()) - tw->setTabToolTip(i, Project::instance()->path()); + if (tw) for (int i = 0; i < tw->count(); i++) + if (tw->tabText(i) == w->windowTitle()) + tw->setTabToolTip(i, Project::instance()->path()); } - entries=projectStateGroup.readEntry("Entries",entries); + entries = projectStateGroup.readEntry("Entries", entries); - files=projectStateGroup.readEntry("Files",files); - mergeFiles=projectStateGroup.readEntry("MergeFiles",mergeFiles); - dockWidgets=projectStateGroup.readEntry("DockWidgets",dockWidgets); - int i=files.size(); - int activeSWIndex=projectStateGroup.readEntry("Active",-1); + files = projectStateGroup.readEntry("Files", files); + mergeFiles = projectStateGroup.readEntry("MergeFiles", mergeFiles); + dockWidgets = projectStateGroup.readEntry("DockWidgets", dockWidgets); + int i = files.size(); + int activeSWIndex = projectStateGroup.readEntry("Active", -1); QStringList failedFiles; - while (--i>=0) - { - if (i= 0) { + if (i < dockWidgets.size()) + m_lastEditorState = dockWidgets.at(i); + if (!fileOpen(files.at(i), entries.at(i)/*, offsets.at(i)*//*,&activeSW11*/, activeSWIndex == i, mergeFiles.at(i),/*silent*/true)) failedFiles.append(files.at(i)); } - if (!failedFiles.isEmpty()) - { - qCDebug(LOKALIZE_LOG)<<"failedFiles"<
  • "+failedFiles.join("
  • ")+"
  • " ); - KNotification* notification=new KNotification("FilesOpenError", this); - notification->setText( i18nc("@info","Error opening the following files:\n\n")%""%failedFiles.join("
    ")%"" ); + KNotification* notification = new KNotification("FilesOpenError", this); + notification->setText(i18nc("@info", "Error opening the following files:\n\n") % "" % failedFiles.join("
    ") % ""); notification->sendEvent(); } if (files.isEmpty() && dockWidgets.size() > 0) - m_lastEditorState=dockWidgets.first(); // restore last state if no editor open + m_lastEditorState = dockWidgets.first(); // restore last state if no editor open - if (activeSWIndex==-1) - { - m_toBeActiveSubWindow=m_projectSubWindow; + if (activeSWIndex == -1) { + m_toBeActiveSubWindow = m_projectSubWindow; QTimer::singleShot(0, this, &LokalizeMainWindow::applyToBeActiveSubWindow); } @@ -774,7 +737,7 @@ void LokalizeMainWindow::widgetTextCapture() { - WidgetTextCaptureConfig* w=new WidgetTextCaptureConfig(this); + WidgetTextCaptureConfig* w = new WidgetTextCaptureConfig(this); w->show(); } @@ -791,76 +754,72 @@ class MyScriptingPlugin: public Kross::ScriptingPlugin { public: - MyScriptingPlugin(QObject* lokalize,QObject* editor) + MyScriptingPlugin(QObject* lokalize, QObject* editor) : Kross::ScriptingPlugin(lokalize) { - addObject(lokalize,"Lokalize"); - addObject(Project::instance(),"Project"); - addObject(editor,"Editor"); - setXMLFile("scriptsui.rc",true); + addObject(lokalize, "Lokalize"); + addObject(Project::instance(), "Project"); + addObject(editor, "Editor"); + setXMLFile("scriptsui.rc", true); } - ~MyScriptingPlugin(){} + ~MyScriptingPlugin() {} }; #define PROJECTRCFILE "scripts.rc" #define PROJECTRCFILEDIR Project::instance()->projectDir()+"/lokalize-scripts" #define PROJECTRCFILEPATH Project::instance()->projectDir()+"/lokalize-scripts" "/" PROJECTRCFILE //TODO be lazy creating scripts dir ProjectScriptingPlugin::ProjectScriptingPlugin(QObject* lokalize, QObject* editor) - : Kross::ScriptingPlugin(Project::instance()->kind(), - PROJECTRCFILEPATH, - Project::instance()->kind(), lokalize) + : Kross::ScriptingPlugin(Project::instance()->kind(), + PROJECTRCFILEPATH, + Project::instance()->kind(), lokalize) { if (Project::instance()->projectDir().isEmpty()) return; - QString filepath=PROJECTRCFILEPATH; + QString filepath = PROJECTRCFILEPATH; // Remove directory "scripts.rc" if it is empty. It could be // mistakenly created by Lokalize 15.04.x. - if (QFileInfo(filepath).isDir() && !QDir().rmdir(filepath)) - { + if (QFileInfo(filepath).isDir() && !QDir().rmdir(filepath)) { qCCritical(LOKALIZE_LOG) << "Failed to remove directory" << filepath << - "to create scripting configuration file with at the same path. " << - "The directory may be not empty."; + "to create scripting configuration file with at the same path. " << + "The directory may be not empty."; return; } - if (!QFile::exists(filepath)) - { + if (!QFile::exists(filepath)) { QDir().mkdir(QFileInfo(filepath).dir().path()); QFile f(filepath); if (!f.open(QIODevice::WriteOnly)) return; QTextStream out(&f); - out <<""; + out << ""; f.close(); } //qCWarning(LOKALIZE_LOG)<collection(Project::instance()->kind()); + Kross::ActionCollection* collection = Kross::Manager::self().actionCollection()->collection(Project::instance()->kind()); if (!collection) return; - foreach(const QString &collectionname, collection->collections()) - { + foreach (const QString &collectionname, collection->collections()) { Kross::ActionCollection* c = collection->collection(collectionname); - if(!c->isEnabled()) continue; + if (!c->isEnabled()) continue; - foreach(Kross::Action* action, c->actions()) - { + foreach (Kross::Action* action, c->actions()) { if (action->property("autorun").toBool()) action->trigger(); if (action->property("first-run").toBool() && Project::local()->firstRun()) @@ -871,15 +830,15 @@ ProjectScriptingPlugin::~ProjectScriptingPlugin() { - Kross::ActionCollection* collection=Kross::Manager::self().actionCollection()->collection(Project::instance()->kind()); + Kross::ActionCollection* collection = Kross::Manager::self().actionCollection()->collection(Project::instance()->kind()); if (!collection) return; - QString scriptsrc=PROJECTRCFILE; + QString scriptsrc = PROJECTRCFILE; QDir rcdir(PROJECTRCFILEDIR); - qCWarning(LOKALIZE_LOG)<readXmlFile(rcdir.absoluteFilePath(rc)); + qCWarning(LOKALIZE_LOG) << rcdir.entryList(QStringList("*.rc"), QDir::Files); + foreach (const QString& rc, QDir(PROJECTRCFILEDIR).entryList(QStringList("*.rc"), QDir::Files)) + if (rc != scriptsrc) + qCWarning(LOKALIZE_LOG) << rc << collection->readXmlFile(rcdir.absoluteFilePath(rc)); } /* @@ -907,48 +866,47 @@ //qCWarning(LOKALIZE_LOG)<registeredServiceNames().value(); #ifndef Q_OS_MAC //TODO really fix!!! - guiFactory()->addClient(new MyScriptingPlugin(this,m_multiEditorAdaptor)); + guiFactory()->addClient(new MyScriptingPlugin(this, m_multiEditorAdaptor)); #endif //QMenu* projectActions=static_cast(factory()->container("project_actions",this)); -/* - KActionCollection* actionCollection = mWindow->actionCollection(); - actionCollection->action("file_save")->setEnabled(canSave); - actionCollection->action("file_save_as")->setEnabled(canSave); -*/ + /* + KActionCollection* actionCollection = mWindow->actionCollection(); + actionCollection->action("file_save")->setEnabled(canSave); + actionCollection->action("file_save_as")->setEnabled(canSave); + */ } void LokalizeMainWindow::loadProjectScripts() { - if (m_projectScriptingPlugin) - { + if (m_projectScriptingPlugin) { guiFactory()->removeClient(m_projectScriptingPlugin); delete m_projectScriptingPlugin; } //a HACK to get new .rc files shown w/o requiring a restart - m_projectScriptingPlugin=new ProjectScriptingPlugin(this,m_multiEditorAdaptor); + m_projectScriptingPlugin = new ProjectScriptingPlugin(this, m_multiEditorAdaptor); //guiFactory()->addClient(m_projectScriptingPlugin); //guiFactory()->removeClient(m_projectScriptingPlugin); delete m_projectScriptingPlugin; - m_projectScriptingPlugin=new ProjectScriptingPlugin(this,m_multiEditorAdaptor); + m_projectScriptingPlugin = new ProjectScriptingPlugin(this, m_multiEditorAdaptor); guiFactory()->addClient(m_projectScriptingPlugin); } int LokalizeMainWindow::lookupInTranslationMemory(DocPosition::Part part, const QString& text) { - TM::TMTab* w=showTM(); + TM::TMTab* w = showTM(); if (!text.isEmpty()) - w->lookup(part==DocPosition::Source?text:QString(),part==DocPosition::Target?text:QString()); + w->lookup(part == DocPosition::Source ? text : QString(), part == DocPosition::Target ? text : QString()); return w->dbusId(); } int LokalizeMainWindow::lookupInTranslationMemory(const QString& source, const QString& target) { - TM::TMTab* w=showTM(); + TM::TMTab* w = showTM(); w->lookup(source, target); return w->dbusId(); } @@ -959,7 +917,7 @@ /*activateWindow(); raise(); show();*/ - return lookupInTranslationMemory(DocPosition::UndefPart,QString()); + return lookupInTranslationMemory(DocPosition::UndefPart, QString()); } int LokalizeMainWindow::openFileInEditorAt(const QString& path, const QString& source, const QString& ctxt) @@ -971,36 +929,39 @@ int LokalizeMainWindow::openFileInEditor(const QString& path) { - return openFileInEditorAt(path,QString(),QString()); + return openFileInEditorAt(path, QString(), QString()); } QObject* LokalizeMainWindow::activeEditor() { //QList editors=m_mdiArea->subWindowList(); - QMdiSubWindow* activeSW=m_mdiArea->currentSubWindow(); + QMdiSubWindow* activeSW = m_mdiArea->currentSubWindow(); if (!activeSW || !qobject_cast(activeSW->widget())) return 0; return activeSW->widget(); } QObject* LokalizeMainWindow::editorForFile(const QString& path) { - FileToEditor::const_iterator it=m_fileToEditor.constFind(QFileInfo(path).canonicalFilePath()); - if (it==m_fileToEditor.constEnd()) return 0; - QMdiSubWindow* w=it.value(); + FileToEditor::const_iterator it = m_fileToEditor.constFind(QFileInfo(path).canonicalFilePath()); + if (it == m_fileToEditor.constEnd()) return 0; + QMdiSubWindow* w = it.value(); if (!w) return 0; return static_cast(w->widget()); } int LokalizeMainWindow::editorIndexForFile(const QString& path) { - EditorTab* editor=static_cast(editorForFile(path)); + EditorTab* editor = static_cast(editorForFile(path)); if (!editor) return -1; return editor->dbusId(); } -QString LokalizeMainWindow::currentProject(){return Project::instance()->path();} +QString LokalizeMainWindow::currentProject() +{ + return Project::instance()->path(); +} #ifdef Q_OS_WIN #include @@ -1010,18 +971,25 @@ } #else #include -int LokalizeMainWindow::pid(){ +int LokalizeMainWindow::pid() +{ return getpid(); } #endif -QString LokalizeMainWindow::dbusName(){return QStringLiteral("org.kde.lokalize-%1").arg(pid());} -void LokalizeMainWindow::busyCursor(bool busy){busy?QApplication::setOverrideCursor(Qt::WaitCursor):QApplication::restoreOverrideCursor();} +QString LokalizeMainWindow::dbusName() +{ + return QStringLiteral("org.kde.lokalize-%1").arg(pid()); +} +void LokalizeMainWindow::busyCursor(bool busy) +{ + busy ? QApplication::setOverrideCursor(Qt::WaitCursor) : QApplication::restoreOverrideCursor(); +} // void LokalizeMainWindow::processEvents(){QCoreApplication::processEvents();} MultiEditorAdaptor::MultiEditorAdaptor(EditorTab *parent) - : EditorAdaptor(parent) + : EditorAdaptor(parent) { setObjectName(QStringLiteral("MultiEditorAdaptor")); connect(parent, QOverload::of(&EditorTab::destroyed), this, QOverload::of(&MultiEditorAdaptor::handleParentDestroy)); @@ -1041,29 +1009,29 @@ void MultiEditorAdaptor::handleParentDestroy(QObject* p) { Q_UNUSED(p); - qCWarning(LOKALIZE_LOG)<<"avoiding destroying m_multiEditorAdaptor"; + qCWarning(LOKALIZE_LOG) << "avoiding destroying m_multiEditorAdaptor"; setParent(0); } //END DBus interface DelayedFileOpener::DelayedFileOpener(const QVector& urls, LokalizeMainWindow* lmw) - : QObject() - , m_urls(urls) - , m_lmw(lmw) + : QObject() + , m_urls(urls) + , m_lmw(lmw) { //do the work just after project loading is finished //(i.e. all the files from previous project session are loaded) QTimer::singleShot(1, this, &DelayedFileOpener::doOpen); } void DelayedFileOpener::doOpen() { - int lastIndex=m_urls.count()-1; - for (int i=0;i<=lastIndex;i++) - m_lmw->fileOpen(m_urls.at(i), 0, /*set as active*/i==lastIndex); + int lastIndex = m_urls.count() - 1; + for (int i = 0; i <= lastIndex; i++) + m_lmw->fileOpen(m_urls.at(i), 0, /*set as active*/i == lastIndex); deleteLater(); } diff --git a/src/lokalizesubwindowbase.h b/src/lokalizesubwindowbase.h --- a/src/lokalizesubwindowbase.h +++ b/src/lokalizesubwindowbase.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -39,18 +39,24 @@ */ class LokalizeSubwindowBase: public KMainWindow { -Q_OBJECT + Q_OBJECT public: - LokalizeSubwindowBase(QWidget* parent):KMainWindow(parent){} - virtual ~LokalizeSubwindowBase(){emit aboutToBeClosed();} - virtual KXMLGUIClient* guiClient()=0; + LokalizeSubwindowBase(QWidget* parent): KMainWindow(parent) {} + virtual ~LokalizeSubwindowBase() + { + emit aboutToBeClosed(); + } + virtual KXMLGUIClient* guiClient() = 0; //interface for LokalizeMainWindow - virtual void hideDocks()=0; - virtual void showDocks()=0; + virtual void hideDocks() = 0; + virtual void showDocks() = 0; //bool queryClose(); - virtual QString currentFilePath(){return QString();} + virtual QString currentFilePath() + { + return QString(); + } protected: void reflectNonApprovedCount(int count, int total); @@ -71,10 +77,13 @@ class LokalizeSubwindowBase2: public LokalizeSubwindowBase, public KXMLGUIClient { public: - LokalizeSubwindowBase2(QWidget* parent): LokalizeSubwindowBase(parent),KXMLGUIClient(){} - virtual ~LokalizeSubwindowBase2(){} + LokalizeSubwindowBase2(QWidget* parent): LokalizeSubwindowBase(parent), KXMLGUIClient() {} + virtual ~LokalizeSubwindowBase2() {} - KXMLGUIClient* guiClient(){return (KXMLGUIClient*)this;} + KXMLGUIClient* guiClient() + { + return (KXMLGUIClient*)this; + } }; #else #include @@ -86,10 +95,10 @@ #include "kmainwindow.h" namespace KStandardAction { - /** - * The standard menubar and toolbar actions. - */ - enum StandardAction { +/** + * The standard menubar and toolbar actions. + */ +enum StandardAction { ActionNone, // File Menu @@ -129,16 +138,25 @@ Clear, PasteText, SwitchApplicationLanguage - }; +}; }; class KActionCategory; class KActionCollection { public: KActionCollection(QMainWindow* w); - ~KActionCollection(){qDeleteAll(categories);} - static void setDefaultShortcut(QAction* a, const QKeySequence& s){a->setShortcut(s);} - static void setDefaultShortcuts(QAction* a, const QList& l){a->setShortcuts(l);} + ~KActionCollection() + { + qDeleteAll(categories); + } + static void setDefaultShortcut(QAction* a, const QKeySequence& s) + { + a->setShortcut(s); + } + static void setDefaultShortcuts(QAction* a, const QList& l) + { + a->setShortcuts(l); + } QAction* addAction(const QString& name, QAction* a); @@ -157,20 +175,38 @@ class KActionCategory { public: - KActionCategory(const QString&, KActionCollection* c_):c(c_){c->categories.append(this);} - QAction* addAction( const char* name, QAction* a){return c->addAction(name, a);} - QAction* addAction( const QString& name, QAction* a){return c->addAction(name, a);} - QAction* addAction( const QLatin1String& name, QAction* a){return c->addAction(name, a);} - QAction* addAction( const QString& name){return c->addAction(name, new QAction(name, c->m_mainWindow));} - QAction* addAction( const QString& name, QObject* rcv, const char* slot) - { - QAction* a=new QAction(name, rcv); + KActionCategory(const QString&, KActionCollection* c_): c(c_) + { + c->categories.append(this); + } + QAction* addAction(const char* name, QAction* a) + { + return c->addAction(name, a); + } + QAction* addAction(const QString& name, QAction* a) + { + return c->addAction(name, a); + } + QAction* addAction(const QLatin1String& name, QAction* a) + { + return c->addAction(name, a); + } + QAction* addAction(const QString& name) + { + return c->addAction(name, new QAction(name, c->m_mainWindow)); + } + QAction* addAction(const QString& name, QObject* rcv, const char* slot) + { + QAction* a = new QAction(name, rcv); QObject::connect(a, &QAction::triggered, rcv, slot); return c->addAction(name, a); } QAction* addAction(KStandardAction::StandardAction, QObject* rcv, const char* slot); - static void setDefaultShortcut(QAction* a, const QKeySequence& s){a->setShortcut(s);} + static void setDefaultShortcut(QAction* a, const QKeySequence& s) + { + a->setShortcut(s); + } KActionCollection* c; }; @@ -181,16 +217,22 @@ LokalizeSubwindowBase2(QWidget* parent): KMainWindow(parent), c(new KActionCollection(this)) { } - virtual ~LokalizeSubwindowBase2(){delete c;} - - void setXMLFile(const char*, bool f=false){} - void setXMLFile(const QString&, bool f=false){} - KActionCollection* actionCollection() const{return c;} + virtual ~LokalizeSubwindowBase2() + { + delete c; + } + + void setXMLFile(const char*, bool f = false) {} + void setXMLFile(const QString&, bool f = false) {} + KActionCollection* actionCollection() const + { + return c; + } StatusBarProxy statusBarItems; protected: - void reflectNonApprovedCount(int count, int total){} - void reflectUntranslatedCount(int count, int total){} + void reflectNonApprovedCount(int count, int total) {} + void reflectUntranslatedCount(int count, int total) {} KActionCollection* c; }; #endif diff --git a/src/main.cpp b/src/main.cpp --- a/src/main.cpp +++ b/src/main.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -72,12 +72,10 @@ PCOPYDATASTRUCT pMyCDS; LONG_PTR WINAPI windowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { - if (message == WM_COPYDATA) - { + if (message == WM_COPYDATA) { pMyCDS = (PCOPYDATASTRUCT)lParam; - if (pMyCDS->dwData==FILEPATHMESSAGE) - { - EditorTab* t=Project::instance()->fileOpen(QString::fromUtf8((char*)pMyCDS->lpData)); + if (pMyCDS->dwData == FILEPATHMESSAGE) { + EditorTab* t = Project::instance()->fileOpen(QString::fromUtf8((char*)pMyCDS->lpData)); if (t) t->activateWindow(); } return 0; @@ -98,24 +96,24 @@ QCommandLineParser parser; KAboutData about(QStringLiteral("lokalize"), i18nc("@title", "Lokalize"), LOKALIZE_VERSION, i18n("Computer-aided translation system.\nDo not translate what had already been translated."), KAboutLicense::GPL, i18nc("@info:credit", "(c) 2007-2015 Nick Shaforostoff\n(c) 1999-2006 The KBabel developers") /*, KLocalizedString(), 0, "shafff@ukr.net"*/); - about.addAuthor( i18n("Nick Shaforostoff"), QString(), QStringLiteral("shaforostoff@gmail.com") ); - about.addCredit (i18n("Google Inc."), i18n("sponsored development as part of Google Summer Of Code program"), QString(), QStringLiteral("http://google.com")); - about.addCredit (i18n("NLNet Foundation"), i18n("sponsored XLIFF-related work"), QString(), QStringLiteral("https://nlnet.nl/")); - about.addCredit (i18n("Translate-toolkit"), i18n("provided excellent cross-format converting scripts"), QString(), QStringLiteral("http://translate.sourceforge.net")); - about.addCredit (i18n("Viesturs Zarins"), i18n("project tree merging translation+templates"), QStringLiteral("viesturs.zarins@mii.lu.lv"), QString()); - about.addCredit (i18n("Stephan Johach"), i18n("bug fixing patches"), QStringLiteral("hunsum@gmx.de")); - about.addCredit (i18n("Chusslove Illich"), i18n("bug fixing patches"), QStringLiteral("caslav.ilic@gmx.net")); - about.addCredit (i18n("Jure Repinc"), i18n("testing and bug fixing"), QStringLiteral("jlp@holodeck1.com")); - about.addCredit (i18n("Stefan Asserhall"), i18n("patches"), QStringLiteral("stefan.asserhall@comhem.se")); - about.addCredit (i18n("Papp Laszlo"), i18n("bug fixing patches"), QStringLiteral("djszapi@archlinux.us")); - about.addCredit (i18n("Albert Astals Cid"), i18n("XLIFF improvements"), QStringLiteral("aacid@kde.org")); + about.addAuthor(i18n("Nick Shaforostoff"), QString(), QStringLiteral("shaforostoff@gmail.com")); + about.addCredit(i18n("Google Inc."), i18n("sponsored development as part of Google Summer Of Code program"), QString(), QStringLiteral("http://google.com")); + about.addCredit(i18n("NLNet Foundation"), i18n("sponsored XLIFF-related work"), QString(), QStringLiteral("https://nlnet.nl/")); + about.addCredit(i18n("Translate-toolkit"), i18n("provided excellent cross-format converting scripts"), QString(), QStringLiteral("http://translate.sourceforge.net")); + about.addCredit(i18n("Viesturs Zarins"), i18n("project tree merging translation+templates"), QStringLiteral("viesturs.zarins@mii.lu.lv"), QString()); + about.addCredit(i18n("Stephan Johach"), i18n("bug fixing patches"), QStringLiteral("hunsum@gmx.de")); + about.addCredit(i18n("Chusslove Illich"), i18n("bug fixing patches"), QStringLiteral("caslav.ilic@gmx.net")); + about.addCredit(i18n("Jure Repinc"), i18n("testing and bug fixing"), QStringLiteral("jlp@holodeck1.com")); + about.addCredit(i18n("Stefan Asserhall"), i18n("patches"), QStringLiteral("stefan.asserhall@comhem.se")); + about.addCredit(i18n("Papp Laszlo"), i18n("bug fixing patches"), QStringLiteral("djszapi@archlinux.us")); + about.addCredit(i18n("Albert Astals Cid"), i18n("XLIFF improvements"), QStringLiteral("aacid@kde.org")); #ifndef NOKDE KAboutData::setApplicationData(about); about.setupCommandLine(&parser); //parser.addOption(QCommandLineOption(QStringList() << QLatin1String("source"), i18n( "Source for the merge mode" ), QLatin1String("URL"))); - parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("noprojectscan"), i18n( "Do not scan files of the project."))); - parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("project"), i18n( "Load specified project."), QStringLiteral("filename"))); - parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("+[URL]"), i18n( "Document to open" ))); + parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("noprojectscan"), i18n("Do not scan files of the project."))); + parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("project"), i18n("Load specified project."), QStringLiteral("filename"))); + parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("+[URL]"), i18n("Document to open"))); parser.process(app); about.processCommandLine(&parser); @@ -128,10 +126,10 @@ #endif //qCDebug(LOKALIZE_LOG) is important as it aviods compile 'optimization'. - qCDebug(LOKALIZE_LOG)<(); - qCDebug(LOKALIZE_LOG)<(); - qCDebug(LOKALIZE_LOG)<(); - qCDebug(LOKALIZE_LOG)<(); + qCDebug(LOKALIZE_LOG) << qRegisterMetaType(); + qCDebug(LOKALIZE_LOG) << qRegisterMetaType(); + qCDebug(LOKALIZE_LOG) << qRegisterMetaType(); + qCDebug(LOKALIZE_LOG) << qRegisterMetaType(); qRegisterMetaTypeStreamOperators("InlineTag"); qRegisterMetaTypeStreamOperators("CatalogString"); #ifndef NOKDE @@ -142,8 +140,7 @@ // see if we are starting with session management if (app.isSessionRestored()) kRestoreMainWindows(); - else - { + else { // no session.. just start up normally QString projectFilePath = parser.value(QStringLiteral("project")); @@ -155,18 +152,17 @@ else if (QFileInfo::exists(filePath)) urls.append(filePath); - if (projectFilePath.length()) - { + if (projectFilePath.length()) { // load needs an absolute path // FIXME: I do not know how to handle urls here // bug 245546 regarding symlinks QFileInfo projectFileInfo(projectFilePath); - projectFilePath=projectFileInfo.canonicalFilePath(); + projectFilePath = projectFileInfo.canonicalFilePath(); if (projectFilePath.isEmpty()) - projectFilePath=projectFileInfo.absoluteFilePath(); - Project::instance()->load( projectFilePath ); + projectFilePath = projectFileInfo.absoluteFilePath(); + Project::instance()->load(projectFilePath); } - LokalizeMainWindow* lmw=new LokalizeMainWindow; + LokalizeMainWindow* lmw = new LokalizeMainWindow; SettingsController::instance()->setMainWindowPtr(lmw); lmw->show(); @@ -180,17 +176,15 @@ TCHAR gClassName[100]; wsprintf(gClassName, TEXT("LokalizeResponder")); - HWND responder=FindWindow(gClassName, L"LokalizeResponder"); - if (responder) - { - for (int j=0; jensureProjectIsLoaded(); - for (int j=0; jfileOpen(parser.positionalArguments().at(j)); - if (!parser.positionalArguments().count()) - { - WelcomeTab* welcome=new WelcomeTab(0); + if (!parser.positionalArguments().count()) { + WelcomeTab* welcome = new WelcomeTab(0); welcome->move(QApplication::desktop()->screen()->rect().center() - welcome->rect().center()); welcome->show(); } app.installEventFilter(Project::instance()); #endif - int code=app.exec(); + int code = app.exec(); #ifdef NOKDE #ifdef Q_OS_WIN @@ -241,17 +234,16 @@ if (Project::instance()->isLoaded()) Project::instance()->save(); - qCWarning(LOKALIZE_LOG)<<"Finishing Project jobs..."; - qCWarning(LOKALIZE_LOG)<<"Finishing TM jobs..."; - int secs=5; - while(--secs>=0) - { + qCWarning(LOKALIZE_LOG) << "Finishing Project jobs..."; + qCWarning(LOKALIZE_LOG) << "Finishing TM jobs..."; + int secs = 5; + while (--secs >= 0) { Project::instance()->model()->threadPool()->waitForDone(1000); TM::threadPool()->waitForDone(1000); QThreadPool::globalInstance()->waitForDone(1000); //qCDebug(LOKALIZE_LOG)<<"QCoreApplication::processEvents()..."; QCoreApplication::processEvents(); - QCoreApplication::sendPostedEvents(0,0); + QCoreApplication::sendPostedEvents(0, 0); } #else Settings::self()->save(); diff --git a/src/mergemode/mergecatalog.h b/src/mergemode/mergecatalog.h --- a/src/mergemode/mergecatalog.h +++ b/src/mergemode/mergecatalog.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -31,30 +31,29 @@ class KAutoSaveFile; -struct MatchItem -{ - int mergeEntry:32; - int baseEntry:32; - short score:16; - short translationIsDifferent:16; +struct MatchItem { + int mergeEntry: 32; + int baseEntry: 32; + short score: 16; + short translationIsDifferent: 16; MatchItem() - : mergeEntry(0) - , baseEntry(0) - , score(0) - , translationIsDifferent(false) + : mergeEntry(0) + , baseEntry(0) + , score(0) + , translationIsDifferent(false) {} MatchItem(int m, int b, bool d) - : mergeEntry(m) - , baseEntry(b) - , score(0) - , translationIsDifferent(d) + : mergeEntry(m) + , baseEntry(b) + , score(0) + , translationIsDifferent(d) {} bool operator<(const MatchItem& other) const { - return score differentEntries()const {return m_mergeDiffIndex;} + int firstChangedIndex() const + { + return m_mergeDiffIndex.isEmpty() ? numberOfEntries() : m_mergeDiffIndex.first(); + } + int lastChangedIndex() const + { + return m_mergeDiffIndex.isEmpty() ? -1 : m_mergeDiffIndex.last(); + } + int nextChangedIndex(uint index) const + { + return findNextInList(m_mergeDiffIndex, index); + } + int prevChangedIndex(uint index) const + { + return findPrevInList(m_mergeDiffIndex, index); + } + int isDifferent(uint index) const + { + return m_mergeDiffIndex.contains(index); + } + QLinkedList differentEntries()const + { + return m_mergeDiffIndex; + } //override to use map QString msgstr(const DocPosition&) const; bool isApproved(uint index) const; bool isPlural(uint index) const; TargetState state(const DocPosition& pos) const; - int unmatchedCount()const{return m_unmatchedCount;} + int unmatchedCount()const + { + return m_unmatchedCount; + } /// whether 'merge source' has entry with such msgid bool isPresent(const int& entry) const; bool isModified(DocPos)const; - bool isModified()const{return m_modified;} + bool isModified()const + { + return m_modified; + } ///@arg pos in baseCatalog's coordinates void copyToBaseCatalog(DocPosition& pos); - enum CopyToBaseOptions {EmptyOnly=1, HigherOnly=2}; - void copyToBaseCatalog(int options=0); + enum CopyToBaseOptions {EmptyOnly = 1, HigherOnly = 2}; + void copyToBaseCatalog(int options = 0); - inline void removeFromDiffIndex(uint index){m_mergeDiffIndex.removeAll(index);} - enum CopyFromBaseOptions {EvenIfNotInDiffIndex=1}; + inline void removeFromDiffIndex(uint index) + { + m_mergeDiffIndex.removeAll(index); + } + enum CopyFromBaseOptions {EvenIfNotInDiffIndex = 1}; void copyFromBaseCatalog(const DocPosition&, int options); - void copyFromBaseCatalog(const DocPosition& pos){copyFromBaseCatalog(pos, EvenIfNotInDiffIndex);} + void copyFromBaseCatalog(const DocPosition& pos) + { + copyFromBaseCatalog(pos, EvenIfNotInDiffIndex); + } public slots: - void copyFromBaseCatalogIfInDiffIndex(const DocPosition& pos){copyFromBaseCatalog(pos, 0);} + void copyFromBaseCatalogIfInDiffIndex(const DocPosition& pos) + { + copyFromBaseCatalog(pos, 0); + } bool save(); //reimplement to do save only when changes were actually done to this catalog private: - MatchItem calcMatchItem(const DocPosition& basePos,const DocPosition& mergePos); - KAutoSaveFile* checkAutoSave(const QString&){return 0;}//rely on basecatalog restore + MatchItem calcMatchItem(const DocPosition& basePos, const DocPosition& mergePos); + KAutoSaveFile* checkAutoSave(const QString&) + { + return 0; //rely on basecatalog restore + } private: diff --git a/src/mergemode/mergecatalog.cpp b/src/mergemode/mergecatalog.cpp --- a/src/mergemode/mergecatalog.cpp +++ b/src/mergemode/mergecatalog.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -34,123 +34,118 @@ MergeCatalog::MergeCatalog(QObject* parent, Catalog* baseCatalog, bool saveChanges) - : Catalog(parent) - , m_baseCatalog(baseCatalog) - , m_unmatchedCount(0) - , m_modified(false) + : Catalog(parent) + , m_baseCatalog(baseCatalog) + , m_unmatchedCount(0) + , m_modified(false) { - setActivePhase(baseCatalog->activePhase(),baseCatalog->activePhaseRole()); - if (saveChanges) - { + setActivePhase(baseCatalog->activePhase(), baseCatalog->activePhaseRole()); + if (saveChanges) { connect(baseCatalog, &Catalog::signalEntryModified, this, &MergeCatalog::copyFromBaseCatalogIfInDiffIndex); connect(baseCatalog, QOverload<>::of(&Catalog::signalFileSaved), this, &MergeCatalog::save); } } void MergeCatalog::copyFromBaseCatalog(const DocPosition& pos, int options) { - bool a=m_mergeDiffIndex.contains(pos.entry); - if (options&EvenIfNotInDiffIndex || !a) - { + bool a = m_mergeDiffIndex.contains(pos.entry); + if (options & EvenIfNotInDiffIndex || !a) { //sync changes - DocPosition ourPos=pos; - if ( (ourPos.entry=m_map.at(ourPos.entry)) == -1) + DocPosition ourPos = pos; + if ((ourPos.entry = m_map.at(ourPos.entry)) == -1) return; //note the explicit use of map... - if (m_storage->isApproved(ourPos)!=m_baseCatalog->isApproved(pos)) + if (m_storage->isApproved(ourPos) != m_baseCatalog->isApproved(pos)) //qCWarning(LOKALIZE_LOG)<setApproved(ourPos, m_baseCatalog->isApproved(pos)); DocPos p(pos); if (!m_originalHashes.contains(p)) - m_originalHashes[p]=qHash(m_storage->target(ourPos)); - m_storage->setTarget(ourPos,m_baseCatalog->target(pos)); + m_originalHashes[p] = qHash(m_storage->target(ourPos)); + m_storage->setTarget(ourPos, m_baseCatalog->target(pos)); setModified(ourPos, true); - if (options&EvenIfNotInDiffIndex && a) + if (options & EvenIfNotInDiffIndex && a) m_mergeDiffIndex.removeAll(pos.entry); - m_modified=true; + m_modified = true; emit signalEntryModified(pos); } } QString MergeCatalog::msgstr(const DocPosition& pos) const { - DocPosition us=pos; - us.entry=m_map.at(pos.entry); + DocPosition us = pos; + us.entry = m_map.at(pos.entry); - return (us.entry==-1)?QString():Catalog::msgstr(us); + return (us.entry == -1) ? QString() : Catalog::msgstr(us); } bool MergeCatalog::isApproved(uint index) const { - return (m_map.at(index)==-1)?false:Catalog::isApproved(m_map.at(index)); + return (m_map.at(index) == -1) ? false : Catalog::isApproved(m_map.at(index)); } TargetState MergeCatalog::state(const DocPosition& pos) const { - DocPosition us=pos; - us.entry=m_map.at(pos.entry); + DocPosition us = pos; + us.entry = m_map.at(pos.entry); - return (us.entry==-1)?New:Catalog::state(us); + return (us.entry == -1) ? New : Catalog::state(us); } bool MergeCatalog::isPlural(uint index) const { //sanity - if (m_map.at(index) == -1) - { - qCWarning(LOKALIZE_LOG)<<"!!! index"<m_storage); - CatalogStorage& mergeStorage=*(m_storage); + CatalogStorage& baseStorage = *(m_baseCatalog->m_storage); + CatalogStorage& mergeStorage = *(m_storage); MatchItem item(mergePos.entry, basePos.entry, true); //TODO make more robust, perhaps after XLIFF? - QStringList baseMatchData=baseStorage.matchData(basePos); - QStringList mergeMatchData=mergeStorage.matchData(mergePos); + QStringList baseMatchData = baseStorage.matchData(basePos); + QStringList mergeMatchData = mergeStorage.matchData(mergePos); - //compare ids - item.score+=40*((baseMatchData.isEmpty()&&mergeMatchData.isEmpty())?baseStorage.id(basePos)==mergeStorage.id(mergePos) - :baseMatchData==mergeMatchData); + //compare ids + item.score += 40 * ((baseMatchData.isEmpty() && mergeMatchData.isEmpty()) ? baseStorage.id(basePos) == mergeStorage.id(mergePos) + : baseMatchData == mergeMatchData); //TODO look also for changed/new s //translation isn't changed - if (baseStorage.targetAllForms(basePos, true)==mergeStorage.targetAllForms(mergePos, true)) - { - item.translationIsDifferent=baseStorage.isApproved(basePos)!=mergeStorage.isApproved(mergePos); - item.score+=29+1*item.translationIsDifferent; + if (baseStorage.targetAllForms(basePos, true) == mergeStorage.targetAllForms(mergePos, true)) { + item.translationIsDifferent = baseStorage.isApproved(basePos) != mergeStorage.isApproved(mergePos); + item.score += 29 + 1 * item.translationIsDifferent; } #if 0 - if (baseStorage.source(basePos)=="%1 (%2)") - { - qCDebug(LOKALIZE_LOG)<<"BASE"; - qCDebug(LOKALIZE_LOG)<url(); - qCDebug(LOKALIZE_LOG)<url(); + qCDebug(LOKALIZE_LOG) << basePos.entry; + qCDebug(LOKALIZE_LOG) << baseStorage.source(basePos); + qCDebug(LOKALIZE_LOG) << baseMatchData.first(); + qCDebug(LOKALIZE_LOG) << "MERGE"; + qCDebug(LOKALIZE_LOG) << url(); + qCDebug(LOKALIZE_LOG) << mergePos.entry; + qCDebug(LOKALIZE_LOG) << mergeStorage.source(mergePos); + qCDebug(LOKALIZE_LOG) << mergeStorage.matchData(mergePos).first(); + qCDebug(LOKALIZE_LOG) << item.score; + qCDebug(LOKALIZE_LOG) << ""; } #endif return item; @@ -164,46 +159,43 @@ int MergeCatalog::loadFromUrl(const QString& filePath) { - int errorLine=Catalog::loadFromUrl(filePath); - if (Q_UNLIKELY( errorLine!=0 )) + int errorLine = Catalog::loadFromUrl(filePath); + if (Q_UNLIKELY(errorLine != 0)) return errorLine; //now calc the entry mapping - CatalogStorage& baseStorage=*(m_baseCatalog->m_storage); - CatalogStorage& mergeStorage=*(m_storage); + CatalogStorage& baseStorage = *(m_baseCatalog->m_storage); + CatalogStorage& mergeStorage = *(m_storage); DocPosition i(0); - int size=baseStorage.size(); - int mergeSize=mergeStorage.size(); - m_map.fill(-1,size); - QMultiMap backMap; //will be used to maintain one-to-one relation + int size = baseStorage.size(); + int mergeSize = mergeStorage.size(); + m_map.fill(-1, size); + QMultiMap backMap; //will be used to maintain one-to-one relation //precalc for fast lookup QMultiHash mergeMap; - while (i.entry& entries=mergeMap.values(key); + i.entry = 0; + while (i.entry < size) { + QString key = strip(baseStorage.source(i)); + const QList& entries = mergeMap.values(key); QList scores; - int k=entries.size(); - if (k) - { - while(--k>=0) - scores<= 0) + scores << calcMatchItem(i, DocPosition(entries.at(k))); qSort(scores.begin(), scores.end(), qGreater()); - m_map[i.entry]=scores.first().mergeEntry; + m_map[i.entry] = scores.first().mergeEntry; backMap.insert(scores.first().mergeEntry, i.entry); if (scores.first().translationIsDifferent) @@ -215,80 +207,76 @@ //maintain one-to-one relation - const QList& mergePositions=backMap.uniqueKeys(); - foreach(int mergePosition, mergePositions) - { - const QList& basePositions=backMap.values(mergePosition); - if (basePositions.size()==1) + const QList& mergePositions = backMap.uniqueKeys(); + foreach (int mergePosition, mergePositions) { + const QList& basePositions = backMap.values(mergePosition); + if (basePositions.size() == 1) continue; //qCDebug(LOKALIZE_LOG)<<"kv"< scores; - foreach(int value, basePositions) - scores<()); - int i=scores.size(); - while(--i>0) - { + int i = scores.size(); + while (--i > 0) { //qCDebug(LOKALIZE_LOG)<<"erasing"<::iterator it = mergeMap.begin(); - while (it != mergeMap.end()) - { - //qCWarning(LOKALIZE_LOG)<::iterator it = mergeMap.begin(); + while (it != mergeMap.end()) + { + //qCWarning(LOKALIZE_LOG)<msgstr(pos)!=msgstr(pos); + bool changeContents = m_baseCatalog->msgstr(pos) != msgstr(pos); - m_baseCatalog->beginMacro(i18nc("@item Undo action item","Accept change in translation")); + m_baseCatalog->beginMacro(i18nc("@item Undo action item", "Accept change in translation")); - if ( m_baseCatalog->state(pos) != state(pos)) - SetStateCmd::instantiateAndPush(m_baseCatalog,pos,state(pos)); + if (m_baseCatalog->state(pos) != state(pos)) + SetStateCmd::instantiateAndPush(m_baseCatalog, pos, state(pos)); - if (changeContents) - { - pos.offset=0; + if (changeContents) { + pos.offset = 0; if (!m_baseCatalog->msgstr(pos).isEmpty()) - m_baseCatalog->push(new DelTextCmd(m_baseCatalog,pos,m_baseCatalog->msgstr(pos))); + m_baseCatalog->push(new DelTextCmd(m_baseCatalog, pos, m_baseCatalog->msgstr(pos))); - m_baseCatalog->push(new InsTextCmd(m_baseCatalog,pos,msgstr(pos))); + m_baseCatalog->push(new InsTextCmd(m_baseCatalog, pos, msgstr(pos))); } ////////this is NOT done automatically by BaseCatalogEntryChanged slot - bool remove=true; - if (isPlural(pos.entry)) - { - DocPosition p=pos; - p.form=qMin(m_baseCatalog->numberOfPluralForms(),numberOfPluralForms());//just sanity check - p.form=qMax((int)p.form,1);//just sanity check - while ((--(p.form))>=0 && remove) - remove=m_baseCatalog->msgstr(p)==msgstr(p); + bool remove = true; + if (isPlural(pos.entry)) { + DocPosition p = pos; + p.form = qMin(m_baseCatalog->numberOfPluralForms(), numberOfPluralForms()); //just sanity check + p.form = qMax((int)p.form, 1); //just sanity check + while ((--(p.form)) >= 0 && remove) + remove = m_baseCatalog->msgstr(p) == msgstr(p); } if (remove) removeFromDiffIndex(pos.entry); @@ -299,33 +287,29 @@ void MergeCatalog::copyToBaseCatalog(int options) { DocPosition pos; - pos.offset=0; - bool insHappened=false; - QLinkedList changed=differentEntries(); - foreach(int entry, changed) - { - pos.entry=entry; - if (options&EmptyOnly&&!m_baseCatalog->isEmpty(entry)) + pos.offset = 0; + bool insHappened = false; + QLinkedList changed = differentEntries(); + foreach (int entry, changed) { + pos.entry = entry; + if (options & EmptyOnly && !m_baseCatalog->isEmpty(entry)) continue; - if (options&HigherOnly&&!m_baseCatalog->isEmpty(entry)&&m_baseCatalog->state(pos)>=state(pos)) + if (options & HigherOnly && !m_baseCatalog->isEmpty(entry) && m_baseCatalog->state(pos) >= state(pos)) continue; - int formsCount=(m_baseCatalog->isPlural(entry))?m_baseCatalog->numberOfPluralForms():1; - pos.form=0; - while (pos.formisPlural(entry)) ? m_baseCatalog->numberOfPluralForms() : 1; + pos.form = 0; + while (pos.form < formsCount) { //m_baseCatalog->push(new DelTextCmd(m_baseCatalog,pos,m_baseCatalog->msgstr(pos.entry,0))); ? //some forms may still contain translation... - if (!(options&EmptyOnly && !m_baseCatalog->isEmpty(pos)) /*&& - !(options&HigherOnly && !m_baseCatalog->isEmpty(pos) && m_baseCatalog->state(pos)>=state(pos))*/) - { - if (!insHappened) - { + if (!(options & EmptyOnly && !m_baseCatalog->isEmpty(pos)) /*&& + !(options&HigherOnly && !m_baseCatalog->isEmpty(pos) && m_baseCatalog->state(pos)>=state(pos))*/) { + if (!insHappened) { //stop basecatalog from sending signalEntryModified to us //when we are the ones who does the modification disconnect(m_baseCatalog, &Catalog::signalEntryModified, this, &MergeCatalog::copyFromBaseCatalogIfInDiffIndex); - insHappened=true; - m_baseCatalog->beginMacro(i18nc("@item Undo action item","Accept all new translations")); + insHappened = true; + m_baseCatalog->beginMacro(i18nc("@item Undo action item", "Accept all new translations")); } copyToBaseCatalog(pos); @@ -340,8 +324,7 @@ /// /// } - if (insHappened) - { + if (insHappened) { m_baseCatalog->endMacro(); //reconnect to catch all modifications coming from outside connect(m_baseCatalog, &Catalog::signalEntryModified, this, &MergeCatalog::copyFromBaseCatalogIfInDiffIndex); diff --git a/src/mergemode/mergeview.h b/src/mergemode/mergeview.h --- a/src/mergemode/mergeview.h +++ b/src/mergemode/mergeview.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -41,7 +41,7 @@ Q_OBJECT public: - MergeView(QWidget*,Catalog*,bool primary); + MergeView(QWidget*, Catalog*, bool primary); virtual ~MergeView(); void dragEnterEvent(QDragEnterEvent* event); @@ -60,12 +60,12 @@ bool event(QEvent *event); public slots: - void mergeOpen(QString mergeFilePath=QString()); + void mergeOpen(QString mergeFilePath = QString()); void cleanup(); void slotNewEntryDisplayed(const DocPosition&); void slotUpdate(const DocPosition&); - void gotoNextChanged(bool approvedOnly=false); + void gotoNextChanged(bool approvedOnly = false); void gotoNextChangedApproved(); void gotoPrevChanged(); void mergeAccept(); @@ -80,7 +80,7 @@ void signalNextChangedAvailable(bool); void signalEntryWithMergeDisplayed(bool); - void gotoEntry(const DocPosition&,int); + void gotoEntry(const DocPosition&, int); void mergeCatalogAvailable(bool); void mergeCatalogPointerChanged(MergeCatalog* mergeCatalog); diff --git a/src/mergemode/mergeview.cpp b/src/mergemode/mergeview.cpp --- a/src/mergemode/mergeview.cpp +++ b/src/mergemode/mergeview.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -44,20 +44,20 @@ #include MergeView::MergeView(QWidget* parent, Catalog* catalog, bool primary) - : QDockWidget ( primary?i18nc("@title:window that displays difference between current file and 'merge source'","Primary Sync"):i18nc("@title:window that displays difference between current file and 'merge source'","Secondary Sync"), parent) + : QDockWidget(primary ? i18nc("@title:window that displays difference between current file and 'merge source'", "Primary Sync") : i18nc("@title:window that displays difference between current file and 'merge source'", "Secondary Sync"), parent) , m_browser(new QTextEdit(this)) , m_baseCatalog(catalog) , m_mergeCatalog(0) - , m_normTitle(primary? - i18nc("@title:window that displays difference between current file and 'merge source'","Primary Sync"): - i18nc("@title:window that displays difference between current file and 'merge source'","Secondary Sync")) - , m_hasInfoTitle(m_normTitle+" [*]") + , m_normTitle(primary ? + i18nc("@title:window that displays difference between current file and 'merge source'", "Primary Sync") : + i18nc("@title:window that displays difference between current file and 'merge source'", "Secondary Sync")) + , m_hasInfoTitle(m_normTitle + " [*]") , m_hasInfo(false) , m_primary(primary) { - setObjectName(primary?QStringLiteral("mergeView-primary"):QStringLiteral("mergeView-secondary")); + setObjectName(primary ? QStringLiteral("mergeView-primary") : QStringLiteral("mergeView-secondary")); setWidget(m_browser); - setToolTip(i18nc("@info:tooltip","Drop file to be merged into / synced with the current one here, then see context menu options")); + setToolTip(i18nc("@info:tooltip", "Drop file to be merged into / synced with the current one here, then see context menu options")); hide(); @@ -84,7 +84,7 @@ void MergeView::dragEnterEvent(QDragEnterEvent* event) { - if(event->mimeData()->hasUrls() && Catalog::extIsSupported(event->mimeData()->urls().first().path())) + if (event->mimeData()->hasUrls() && Catalog::extIsSupported(event->mimeData()->urls().first().path())) event->acceptProposedAction(); } @@ -96,28 +96,26 @@ void MergeView::slotUpdate(const DocPosition& pos) { - if (pos.entry==m_pos.entry) + if (pos.entry == m_pos.entry) slotNewEntryDisplayed(pos); } void MergeView::slotNewEntryDisplayed(const DocPosition& pos) { - m_pos=pos; + m_pos = pos; if (!m_mergeCatalog) return; - emit signalPriorChangedAvailable((pos.entry>m_mergeCatalog->firstChangedIndex()) - ||(pluralFormsAvailableBackward()!=-1)); - emit signalNextChangedAvailable((pos.entrylastChangedIndex()) - ||(pluralFormsAvailableForward()!=-1)); + emit signalPriorChangedAvailable((pos.entry > m_mergeCatalog->firstChangedIndex()) + || (pluralFormsAvailableBackward() != -1)); + emit signalNextChangedAvailable((pos.entry < m_mergeCatalog->lastChangedIndex()) + || (pluralFormsAvailableForward() != -1)); - if (!m_mergeCatalog->isPresent(pos.entry)) - { + if (!m_mergeCatalog->isPresent(pos.entry)) { //i.e. no corresponding entry, whether changed or not - if (m_hasInfo) - { - m_hasInfo=false; + if (m_hasInfo) { + m_hasInfo = false; setWindowTitle(m_normTitle); m_browser->clear(); // m_browser->viewport()->setBackgroundRole(QPalette::Base); @@ -127,44 +125,38 @@ /// no editing at all! //////////// return; } - if (!m_hasInfo) - { - m_hasInfo=true; + if (!m_hasInfo) { + m_hasInfo = true; setWindowTitle(m_hasInfoTitle); } emit signalEntryWithMergeDisplayed(m_mergeCatalog->isDifferent(pos.entry)); - QString result=userVisibleWordDiff(m_baseCatalog->msgstr(pos), - m_mergeCatalog->msgstr(pos), - Project::instance()->accel(), - Project::instance()->markup(), - Html); + QString result = userVisibleWordDiff(m_baseCatalog->msgstr(pos), + m_mergeCatalog->msgstr(pos), + Project::instance()->accel(), + Project::instance()->markup(), + Html); #if 0 - int i=-1; - bool inTag=false; - while(++i') - inTag=false; + int i = -1; + bool inTag = false; + while (++i < result.size()) { //dynamic + if (!inTag) { + if (result.at(i) == '<') + inTag = true; + else if (result.at(i) == ' ') + result.replace(i, 1, "&sp;"); + } else if (result.at(i) == '>') + inTag = false; } #endif - if (!m_mergeCatalog->isApproved(pos.entry)) - { + if (!m_mergeCatalog->isApproved(pos.entry)) { result.prepend(""); result.append(""); } - if (m_mergeCatalog->isModified(pos)) - { + if (m_mergeCatalog->isModified(pos)) { result.prepend(""); result.append(""); } @@ -176,10 +168,10 @@ void MergeView::cleanup() { delete m_mergeCatalog; - m_mergeCatalog=0; + m_mergeCatalog = 0; emit mergeCatalogPointerChanged(0); emit mergeCatalogAvailable(false); - m_pos=DocPosition(); + m_pos = DocPosition(); emit signalPriorChangedAvailable(false); emit signalNextChangedAvailable(false); @@ -189,66 +181,59 @@ void MergeView::mergeOpen(QString mergeFilePath) { - if (Q_UNLIKELY( !m_baseCatalog->numberOfEntries() )) + if (Q_UNLIKELY(!m_baseCatalog->numberOfEntries())) return; - if (mergeFilePath==m_baseCatalog->url()) - { + if (mergeFilePath == m_baseCatalog->url()) { //(we are likely to be _mergeViewSecondary) //special handling: open corresponding file in the branch //for AutoSync - QString path=QFileInfo(mergeFilePath).canonicalFilePath(); //bug 245546 regarding symlinks - QString oldPath=path; - path.replace(Project::instance()->poDir(),Project::instance()->branchDir()); + QString path = QFileInfo(mergeFilePath).canonicalFilePath(); //bug 245546 regarding symlinks + QString oldPath = path; + path.replace(Project::instance()->poDir(), Project::instance()->branchDir()); - if (oldPath==path) //if file doesn't exist both are empty - { + if (oldPath == path) { //if file doesn't exist both are empty cleanup(); return; } - mergeFilePath=path; + mergeFilePath = path; } - if (mergeFilePath.isEmpty()) - { + if (mergeFilePath.isEmpty()) { //Project::instance()->model()->weaver()->suspend(); //KDE5PORT use mutex if needed - mergeFilePath=QFileDialog::getOpenFileName(this, i18nc("@title:window", "Select translation file"), QString(), Catalog::supportedFileTypes(false)); + mergeFilePath = QFileDialog::getOpenFileName(this, i18nc("@title:window", "Select translation file"), QString(), Catalog::supportedFileTypes(false)); //Project::instance()->model()->weaver()->resume(); } if (mergeFilePath.isEmpty()) return; delete m_mergeCatalog; - m_mergeCatalog=new MergeCatalog(this,m_baseCatalog); + m_mergeCatalog = new MergeCatalog(this, m_baseCatalog); emit mergeCatalogPointerChanged(m_mergeCatalog); emit mergeCatalogAvailable(m_mergeCatalog); - int errorLine=m_mergeCatalog->loadFromUrl(mergeFilePath); - if (Q_LIKELY( errorLine==0 )) - { - if (m_pos.entry>0) - emit signalPriorChangedAvailable(m_pos.entry>m_mergeCatalog->firstChangedIndex()); + int errorLine = m_mergeCatalog->loadFromUrl(mergeFilePath); + if (Q_LIKELY(errorLine == 0)) { + if (m_pos.entry > 0) + emit signalPriorChangedAvailable(m_pos.entry > m_mergeCatalog->firstChangedIndex()); - emit signalNextChangedAvailable(m_pos.entrylastChangedIndex()); + emit signalNextChangedAvailable(m_pos.entry < m_mergeCatalog->lastChangedIndex()); //a bit hacky :) connect(m_mergeCatalog, &MergeCatalog::signalEntryModified, this, &MergeView::slotUpdate); - if (m_pos.entry!=-1) + if (m_pos.entry != -1) slotNewEntryDisplayed(m_pos); show(); - } - else - { + } else { //KMessageBox::error(this, KIO::NetAccess::lastErrorString() ); cleanup(); #ifndef NOKDE - if (errorLine>0) - KMessageBox::error(this, i18nc("@info","Error opening the file %1 for synchronization, error line: %2",mergeFilePath,errorLine) ); - else - { + if (errorLine > 0) + KMessageBox::error(this, i18nc("@info", "Error opening the file %1 for synchronization, error line: %2", mergeFilePath, errorLine)); + else { /* disable this as requested by bug 272587 KNotification* notification=new KNotification("MergeFilesOpenError", this); notification->setText( i18nc("@info %1 is full filename","Error opening the file %1 for synchronization",url.pathOrUrl()) ); @@ -268,54 +253,50 @@ int MergeView::pluralFormsAvailableForward() { - if(Q_LIKELY( m_pos.entry==-1 || !m_mergeCatalog->isPlural(m_pos.entry) )) + if (Q_LIKELY(m_pos.entry == -1 || !m_mergeCatalog->isPlural(m_pos.entry))) return -1; - int formLimit=qMin(m_baseCatalog->numberOfPluralForms(),m_mergeCatalog->numberOfPluralForms());//just sanity check - DocPosition pos=m_pos; - while (++(pos.form)msgstr(pos)!=m_mergeCatalog->msgstr(pos)) + int formLimit = qMin(m_baseCatalog->numberOfPluralForms(), m_mergeCatalog->numberOfPluralForms()); //just sanity check + DocPosition pos = m_pos; + while (++(pos.form) < formLimit) { + if (m_baseCatalog->msgstr(pos) != m_mergeCatalog->msgstr(pos)) return pos.form; } return -1; } int MergeView::pluralFormsAvailableBackward() { - if(Q_LIKELY( m_pos.entry==-1 || !m_mergeCatalog->isPlural(m_pos.entry) )) + if (Q_LIKELY(m_pos.entry == -1 || !m_mergeCatalog->isPlural(m_pos.entry))) return -1; - DocPosition pos=m_pos; - while (--(pos.form)>=0) - { - if (m_baseCatalog->msgstr(pos)!=m_mergeCatalog->msgstr(pos)) + DocPosition pos = m_pos; + while (--(pos.form) >= 0) { + if (m_baseCatalog->msgstr(pos) != m_mergeCatalog->msgstr(pos)) return pos.form; } return -1; } void MergeView::gotoPrevChanged() { - if (Q_UNLIKELY( !m_mergeCatalog )) + if (Q_UNLIKELY(!m_mergeCatalog)) return; DocPosition pos; //first, check if there any plural forms waiting to be synced - int form=pluralFormsAvailableBackward(); - if (Q_UNLIKELY( form!=-1 )) - { - pos=m_pos; - pos.form=form; - } - else if(Q_UNLIKELY( (pos.entry=m_mergeCatalog->prevChangedIndex(m_pos.entry)) == -1 )) + int form = pluralFormsAvailableBackward(); + if (Q_UNLIKELY(form != -1)) { + pos = m_pos; + pos.form = form; + } else if (Q_UNLIKELY((pos.entry = m_mergeCatalog->prevChangedIndex(m_pos.entry)) == -1)) return; - if (Q_UNLIKELY( m_mergeCatalog->isPlural(pos.entry)&&form==-1 )) - pos.form=qMin(m_baseCatalog->numberOfPluralForms(),m_mergeCatalog->numberOfPluralForms())-1; + if (Q_UNLIKELY(m_mergeCatalog->isPlural(pos.entry) && form == -1)) + pos.form = qMin(m_baseCatalog->numberOfPluralForms(), m_mergeCatalog->numberOfPluralForms()) - 1; - emit gotoEntry(pos,0); + emit gotoEntry(pos, 0); } void MergeView::gotoNextChangedApproved() @@ -325,73 +306,69 @@ void MergeView::gotoNextChanged(bool approvedOnly) { - if (Q_UNLIKELY( !m_mergeCatalog )) + if (Q_UNLIKELY(!m_mergeCatalog)) return; - DocPosition pos=m_pos; + DocPosition pos = m_pos; //first, check if there any plural forms waiting to be synced - int form=pluralFormsAvailableForward(); - if (Q_UNLIKELY( form!=-1 )) - { - pos=m_pos; - pos.form=form; - } - else if(Q_UNLIKELY( (pos.entry=m_mergeCatalog->nextChangedIndex(m_pos.entry)) == -1 )) + int form = pluralFormsAvailableForward(); + if (Q_UNLIKELY(form != -1)) { + pos = m_pos; + pos.form = form; + } else if (Q_UNLIKELY((pos.entry = m_mergeCatalog->nextChangedIndex(m_pos.entry)) == -1)) return; - while (approvedOnly && !m_mergeCatalog->isApproved(pos.entry)) - { - if(Q_UNLIKELY( (pos.entry=m_mergeCatalog->nextChangedIndex(pos.entry)) == -1 )) - return; + while (approvedOnly && !m_mergeCatalog->isApproved(pos.entry)) { + if (Q_UNLIKELY((pos.entry = m_mergeCatalog->nextChangedIndex(pos.entry)) == -1)) + return; } - emit gotoEntry(pos,0); + emit gotoEntry(pos, 0); } void MergeView::mergeBack() { - if(m_pos.entry==-1 ||!m_mergeCatalog ||m_baseCatalog->msgstr(m_pos).isEmpty()) + if (m_pos.entry == -1 || !m_mergeCatalog || m_baseCatalog->msgstr(m_pos).isEmpty()) return; m_mergeCatalog->copyFromBaseCatalog(m_pos); } void MergeView::mergeAccept() { - if(m_pos.entry==-1 - ||!m_mergeCatalog - //||m_baseCatalog->msgstr(m_pos)==m_mergeCatalog->msgstr(m_pos) - ||m_mergeCatalog->msgstr(m_pos).isEmpty()) + if (m_pos.entry == -1 + || !m_mergeCatalog + //||m_baseCatalog->msgstr(m_pos)==m_mergeCatalog->msgstr(m_pos) + || m_mergeCatalog->msgstr(m_pos).isEmpty()) return; m_mergeCatalog->copyToBaseCatalog(m_pos); - emit gotoEntry(m_pos,0); + emit gotoEntry(m_pos, 0); } void MergeView::mergeAcceptAllForEmpty() { - if(Q_UNLIKELY(!m_mergeCatalog)) return; + if (Q_UNLIKELY(!m_mergeCatalog)) return; - bool update=m_mergeCatalog->differentEntries().contains(m_pos.entry); + bool update = m_mergeCatalog->differentEntries().contains(m_pos.entry); m_mergeCatalog->copyToBaseCatalog(/*MergeCatalog::EmptyOnly*/MergeCatalog::HigherOnly); - if (update!=m_mergeCatalog->differentEntries().contains(m_pos.entry)) - emit gotoEntry(m_pos,0); + if (update != m_mergeCatalog->differentEntries().contains(m_pos.entry)) + emit gotoEntry(m_pos, 0); } bool MergeView::event(QEvent *event) { - if (event->type()==QEvent::ToolTip && m_mergeCatalog) - { + if (event->type() == QEvent::ToolTip && m_mergeCatalog) { QHelpEvent *helpEvent = static_cast(event); - QString text=QStringLiteral("") % QDir::toNativeSeparators(filePath()) % QStringLiteral("\n") % i18nc("@info:tooltip","Different entries: %1\nUnmatched entries: %2", - m_mergeCatalog->differentEntries().count(),m_mergeCatalog->unmatchedCount()); - text.replace('\n',QStringLiteral("
    ")); - QToolTip::showText(helpEvent->globalPos(),text); + QString text = QStringLiteral("") % QDir::toNativeSeparators(filePath()) % QStringLiteral("\n") % i18nc("@info:tooltip", "Different entries: %1\nUnmatched entries: %2", + m_mergeCatalog->differentEntries().count(), m_mergeCatalog->unmatchedCount()); + text.replace('\n', QStringLiteral("
    ")); + QToolTip::showText(helpEvent->globalPos(), text); return true; } return QWidget::event(event); diff --git a/src/msgctxtview.h b/src/msgctxtview.h --- a/src/msgctxtview.h +++ b/src/msgctxtview.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -40,10 +40,10 @@ Q_OBJECT public: - MsgCtxtView(QWidget*,Catalog*); + MsgCtxtView(QWidget*, Catalog*); ~MsgCtxtView(); - void gotoEntry(const DocPosition&, int selection=0); + void gotoEntry(const DocPosition&, int selection = 0); void addNote(DocPosition, const QString& text); void addTemporaryEntryNote(int entry, const QString& text); public slots: @@ -67,8 +67,8 @@ QStackedLayout* m_stackedLayout; Catalog* m_catalog; - QMap< DocPos,QPair > m_unfinishedNotes;//note and its index - QMap< int,QString > m_tempNotes; + QMap< DocPos, QPair > m_unfinishedNotes; //note and its index + QMap< int, QString > m_tempNotes; int m_selection; int m_offset; bool m_hasInfo; diff --git a/src/msgctxtview.cpp b/src/msgctxtview.cpp --- a/src/msgctxtview.cpp +++ b/src/msgctxtview.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -44,7 +44,7 @@ #include MsgCtxtView::MsgCtxtView(QWidget* parent, Catalog* catalog) - : QDockWidget (i18nc("@title toolview name","Unit metadata"), parent) + : QDockWidget(i18nc("@title toolview name", "Unit metadata"), parent) , m_browser(new QTextBrowser(this)) , m_editor(0) , m_catalog(catalog) @@ -54,14 +54,14 @@ , m_hasErrorNotes(false) { setObjectName(QStringLiteral("msgCtxtView")); - QWidget* main=new QWidget(this); + QWidget* main = new QWidget(this); setWidget(main); m_stackedLayout = new QStackedLayout(main); m_stackedLayout->addWidget(m_browser); m_browser->viewport()->setBackgroundRole(QPalette::Background); m_browser->setOpenLinks(false); - connect(m_browser,&QTextBrowser::anchorClicked,this,&MsgCtxtView::anchorClicked); + connect(m_browser, &QTextBrowser::anchorClicked, this, &MsgCtxtView::anchorClicked); } MsgCtxtView::~MsgCtxtView() @@ -76,91 +76,85 @@ void MsgCtxtView::gotoEntry(const DocPosition& pos, int selection) { - m_entry=DocPos(pos); - m_selection=selection; - m_offset=pos.offset; + m_entry = DocPos(pos); + m_selection = selection; + m_offset = pos.offset; QTimer::singleShot(0, this, &MsgCtxtView::process); } void MsgCtxtView::process() { - if (m_catalog->numberOfEntries()<=m_entry.entry) + if (m_catalog->numberOfEntries() <= m_entry.entry) return;//because of Qt::QueuedConnection if (m_stackedLayout->currentIndex()) - m_unfinishedNotes[m_prevEntry]=qMakePair(m_editor->note(),m_editor->noteIndex()); + m_unfinishedNotes[m_prevEntry] = qMakePair(m_editor->note(), m_editor->noteIndex()); - if (m_unfinishedNotes.contains(m_entry)) - { + if (m_unfinishedNotes.contains(m_entry)) { addNoteUI(); - m_editor->setNote(m_unfinishedNotes.value(m_entry).first,m_unfinishedNotes.value(m_entry).second); - } - else + m_editor->setNote(m_unfinishedNotes.value(m_entry).first, m_unfinishedNotes.value(m_entry).second); + } else m_stackedLayout->setCurrentIndex(0); - m_prevEntry=m_entry; + m_prevEntry = m_entry; m_browser->clear(); - static const QString BR=QStringLiteral("
    "); - if (m_tempNotes.contains(m_entry.entry)) - { - QString html=i18nc("@info notes to translation unit which expire when the catalog is closed", "Temporary notes:"); - html+=BR; - foreach(const QString& note, m_tempNotes.values(m_entry.entry)) - html+=note.toHtmlEscaped()+BR; - html+=BR; - m_browser->insertHtml(html.replace('\n',BR)); + static const QString BR = QStringLiteral("
    "); + if (m_tempNotes.contains(m_entry.entry)) { + QString html = i18nc("@info notes to translation unit which expire when the catalog is closed", "Temporary notes:"); + html += BR; + foreach (const QString& note, m_tempNotes.values(m_entry.entry)) + html += note.toHtmlEscaped() + BR; + html += BR; + m_browser->insertHtml(html.replace('\n', BR)); } - QString phaseName=m_catalog->phase(m_entry.toDocPosition()); - if (!phaseName.isEmpty()) - { - Phase phase=m_catalog->phase(phaseName); - QString html=i18nc("@info translation unit metadata","Phase:
    "); + QString phaseName = m_catalog->phase(m_entry.toDocPosition()); + if (!phaseName.isEmpty()) { + Phase phase = m_catalog->phase(phaseName); + QString html = i18nc("@info translation unit metadata", "Phase:
    "); if (phase.date.isValid()) - html+=QString(QStringLiteral("%1: ")).arg(phase.date.toString(Qt::ISODate)); - html+=phase.process.toHtmlEscaped(); + html += QString(QStringLiteral("%1: ")).arg(phase.date.toString(Qt::ISODate)); + html += phase.process.toHtmlEscaped(); if (!phase.contact.isEmpty()) - html+=QString(QStringLiteral(" (%1)")).arg(phase.contact.toHtmlEscaped()); - m_browser->insertHtml(html+BR); + html += QString(QStringLiteral(" (%1)")).arg(phase.contact.toHtmlEscaped()); + m_browser->insertHtml(html + BR); } - const QVector notes=m_catalog->notes(m_entry.toDocPosition()); - m_hasErrorNotes=false; + const QVector notes = m_catalog->notes(m_entry.toDocPosition()); + m_hasErrorNotes = false; foreach (const Note& note, notes) - m_hasErrorNotes=m_hasErrorNotes||note.content.contains(QLatin1String("[ERROR]")); + m_hasErrorNotes = m_hasErrorNotes || note.content.contains(QLatin1String("[ERROR]")); - int realOffset=displayNotes(m_browser, m_catalog->notes(m_entry.toDocPosition()), m_entry.form, m_catalog->capabilities()&MultipleNotes); + int realOffset = displayNotes(m_browser, m_catalog->notes(m_entry.toDocPosition()), m_entry.form, m_catalog->capabilities()&MultipleNotes); QString html; - foreach(const Note& note, m_catalog->developerNotes(m_entry.toDocPosition())) - { - html+=BR+escapeWithLinks(note.content); + foreach (const Note& note, m_catalog->developerNotes(m_entry.toDocPosition())) { + html += BR + escapeWithLinks(note.content); } - QStringList sourceFiles=m_catalog->sourceFiles(m_entry.toDocPosition()); - if (!sourceFiles.isEmpty()) - { - html+=i18nc("@info PO comment parsing","
    Files:
    "); - foreach(const QString &sourceFile, sourceFiles) - html+=QString(QStringLiteral("%2
    ")).arg(sourceFile, sourceFile); + QStringList sourceFiles = m_catalog->sourceFiles(m_entry.toDocPosition()); + if (!sourceFiles.isEmpty()) { + html += i18nc("@info PO comment parsing", "
    Files:
    "); + foreach (const QString &sourceFile, sourceFiles) + html += QString(QStringLiteral("%2
    ")).arg(sourceFile, sourceFile); html.chop(6); } - QString msgctxt=m_catalog->context(m_entry.entry).first(); + QString msgctxt = m_catalog->context(m_entry.entry).first(); if (!msgctxt.isEmpty()) - html+=i18nc("@info PO comment parsing","
    Context:
    ")+msgctxt.toHtmlEscaped(); + html += i18nc("@info PO comment parsing", "
    Context:
    ") + msgctxt.toHtmlEscaped(); - QTextCursor t=m_browser->textCursor(); + QTextCursor t = m_browser->textCursor(); t.movePosition(QTextCursor::End); m_browser->setTextCursor(t); m_browser->insertHtml(html); t.movePosition(QTextCursor::Start); - t.movePosition(QTextCursor::NextCharacter,QTextCursor::MoveAnchor,realOffset+m_offset); - t.movePosition(QTextCursor::NextCharacter,QTextCursor::KeepAnchor,m_selection); + t.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, realOffset + m_offset); + t.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, m_selection); m_browser->setTextCursor(t); } @@ -172,52 +166,44 @@ void MsgCtxtView::anchorClicked(const QUrl& link) { - QString path=link.path().mid(1);// minus '/' - - if (link.scheme()==QLatin1String("note")) - { - int capabilities=m_catalog->capabilities(); - if (!m_editor) - { - m_editor=new NoteEditor(this); + QString path = link.path().mid(1); // minus '/' + + if (link.scheme() == QLatin1String("note")) { + int capabilities = m_catalog->capabilities(); + if (!m_editor) { + m_editor = new NoteEditor(this); m_stackedLayout->addWidget(m_editor); connect(m_editor, &NoteEditor::accepted, this, &MsgCtxtView::noteEditAccepted); connect(m_editor, &NoteEditor::rejected, this, &MsgCtxtView::noteEditRejected); } m_editor->setNoteAuthors(m_catalog->noteAuthors()); - QVector notes=m_catalog->notes(m_entry.toDocPosition()); - int noteIndex=-1;//means add new note + QVector notes = m_catalog->notes(m_entry.toDocPosition()); + int noteIndex = -1; //means add new note Note note; - if (!path.endsWith(QLatin1String("add"))) - { - noteIndex=path.toInt(); - note=notes.at(noteIndex); - } - else if (!(capabilities&MultipleNotes) && notes.size()) - { - noteIndex=0; //so we don't overwrite the only possible note - note=notes.first(); + if (!path.endsWith(QLatin1String("add"))) { + noteIndex = path.toInt(); + note = notes.at(noteIndex); + } else if (!(capabilities & MultipleNotes) && notes.size()) { + noteIndex = 0; //so we don't overwrite the only possible note + note = notes.first(); } - m_editor->setNote(note,noteIndex); - m_editor->setFromFieldVisible(capabilities&KeepsNoteAuthors); + m_editor->setNote(note, noteIndex); + m_editor->setFromFieldVisible(capabilities & KeepsNoteAuthors); m_stackedLayout->setCurrentIndex(1); - } - else if (link.scheme()==QLatin1String("src")) - { - int pos=path.lastIndexOf(':'); - emit srcFileOpenRequested(path.left(pos),path.midRef(pos+1).toInt()); - } - else if (link.scheme().contains(QLatin1String("tp"))) + } else if (link.scheme() == QLatin1String("src")) { + int pos = path.lastIndexOf(':'); + emit srcFileOpenRequested(path.left(pos), path.midRef(pos + 1).toInt()); + } else if (link.scheme().contains(QLatin1String("tp"))) QDesktopServices::openUrl(link); } void MsgCtxtView::noteEditAccepted() { - DocPosition pos=m_entry.toDocPosition(); - pos.form=m_editor->noteIndex(); - m_catalog->push(new SetNoteCmd(m_catalog,pos,m_editor->note())); + DocPosition pos = m_entry.toDocPosition(); + pos.form = m_editor->noteIndex(); + m_catalog->push(new SetNoteCmd(m_catalog, pos, m_editor->note())); - m_prevEntry.entry=-1; process(); + m_prevEntry.entry = -1; process(); //m_stackedLayout->setCurrentIndex(0); //m_unfinishedNotes.remove(m_entry); noteEditRejected(); @@ -231,31 +217,33 @@ void MsgCtxtView::addNote(DocPosition p, const QString& text) { - p.form=-1; - m_catalog->push(new SetNoteCmd(m_catalog,p,Note(text))); - if (m_entry.entry==p.entry) {m_prevEntry.entry=-1; process();} + p.form = -1; + m_catalog->push(new SetNoteCmd(m_catalog, p, Note(text))); + if (m_entry.entry == p.entry) { + m_prevEntry.entry = -1; + process(); + } } void MsgCtxtView::addTemporaryEntryNote(int entry, const QString& text) { - m_tempNotes.insertMulti(entry,text); - m_prevEntry.entry=-1; process(); + m_tempNotes.insertMulti(entry, text); + m_prevEntry.entry = -1; process(); } void MsgCtxtView::removeErrorNotes() { if (!m_hasErrorNotes) return; - DocPosition p=m_entry.toDocPosition(); - const QVector notes=m_catalog->notes(p); - p.form=notes.size(); - while(--(p.form)>=0) - { + DocPosition p = m_entry.toDocPosition(); + const QVector notes = m_catalog->notes(p); + p.form = notes.size(); + while (--(p.form) >= 0) { if (notes.at(p.form).content.contains(QLatin1String("[ERROR]"))) - m_catalog->push(new SetNoteCmd(m_catalog,p,Note())); + m_catalog->push(new SetNoteCmd(m_catalog, p, Note())); } - m_prevEntry.entry=-1; process(); + m_prevEntry.entry = -1; process(); } diff --git a/src/multieditoradaptor.h b/src/multieditoradaptor.h --- a/src/multieditoradaptor.h +++ b/src/multieditoradaptor.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -41,7 +41,9 @@ ~MultiEditorAdaptor() { /*qCWarning(LOKALIZE_LOG)<<"bye bye cruel world";*/ } inline EditorTab* editorTab() const - { return static_cast(QObject::parent()); } + { + return static_cast(QObject::parent()); + } void setEditorTab(EditorTab* e); diff --git a/src/nokde-stubs/kaboutdata.h b/src/nokde-stubs/kaboutdata.h --- a/src/nokde-stubs/kaboutdata.h +++ b/src/nokde-stubs/kaboutdata.h @@ -4,24 +4,23 @@ namespace KAboutLicense { - enum L {GPL}; +enum L {GPL}; }; -struct Credit -{ +struct Credit { QString name, what, mail, site; }; class KAboutData: public QObject { Q_OBJECT public: KAboutData(const QString&, const QString& n, const QString& v, const QString& d, KAboutLicense::L, const QString& c); void addAuthor(const QString& name, const QString&, const QString& mail); - void addCredit(const QString& who, const QString& forwhat, const QString& mail, const QString& site=QString()); + void addCredit(const QString& who, const QString& forwhat, const QString& mail, const QString& site = QString()); static KAboutData* instance; public slots: void doAbout(); private: QString name, version, description, copyright; QVector credits; }; \ No newline at end of file diff --git a/src/nokde-stubs/kcombobox.h b/src/nokde-stubs/kcombobox.h --- a/src/nokde-stubs/kcombobox.h +++ b/src/nokde-stubs/kcombobox.h @@ -7,17 +7,16 @@ class KComboBox: public QComboBox { public: - KComboBox(QWidget* p):QComboBox(p){} - void setCurrentItem(const QString& s, bool insert=false) + KComboBox(QWidget* p): QComboBox(p) {} + void setCurrentItem(const QString& s, bool insert = false) { setCurrentText(s); if (insert) - if (QStringListModel* lm=qobject_cast(model())) - { - QStringList l=lm->stringList(); - if (!l.contains(s)) l.append(s); - lm->setStringList(l); - } + if (QStringListModel* lm = qobject_cast(model())) { + QStringList l = lm->stringList(); + if (!l.contains(s)) l.append(s); + lm->setStringList(l); + } } }; diff --git a/src/nokde-stubs/klocalizedstring.h b/src/nokde-stubs/klocalizedstring.h --- a/src/nokde-stubs/klocalizedstring.h +++ b/src/nokde-stubs/klocalizedstring.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -24,31 +24,67 @@ #ifndef KLOCALIZEDSTRING_H #define KLOCALIZEDSTRING_H -#include +#include -static inline QString i18nc(const char* y, const char* x){return QObject::tr(x, y);} -static inline QString i18nc(const char* y, const char* x, int n){return QObject::tr(x, y, n);} -static inline QString i18nc(const char* y, const char* x, const QString& s){return QObject::tr(x, y).arg(s);} -static inline QString i18nc(const char* y, const char* x, const QString& s1, const QString& s2){return QObject::tr(x, y).arg(s1).arg(s2);} -static inline QString i18nc(const char* y, const char* x, int n, int m){return QObject::tr(x, y).arg(n).arg(m);} -static inline QString i18n(const char* x, int n, int m){return QObject::tr(x).arg(n).arg(m);} -static inline QString i18n(const char* x, const QString& s1, const QString& s2){return QObject::tr(x).arg(s1).arg(s2);} -static inline QString i18n(const char* x){return QObject::tr(x);} +static inline QString i18nc(const char* y, const char* x) +{ + return QObject::tr(x, y); +} +static inline QString i18nc(const char* y, const char* x, int n) +{ + return QObject::tr(x, y, n); +} +static inline QString i18nc(const char* y, const char* x, const QString& s) +{ + return QObject::tr(x, y).arg(s); +} +static inline QString i18nc(const char* y, const char* x, const QString& s1, const QString& s2) +{ + return QObject::tr(x, y).arg(s1).arg(s2); +} +static inline QString i18nc(const char* y, const char* x, int n, int m) +{ + return QObject::tr(x, y).arg(n).arg(m); +} +static inline QString i18n(const char* x, int n, int m) +{ + return QObject::tr(x).arg(n).arg(m); +} +static inline QString i18n(const char* x, const QString& s1, const QString& s2) +{ + return QObject::tr(x).arg(s1).arg(s2); +} +static inline QString i18n(const char* x) +{ + return QObject::tr(x); +} namespace KLocalizedString { - void setApplicationDomain(const char*); +void setApplicationDomain(const char*); }; #if 0 QString i18nc(const char* y, const char* x); QString i18nc(const char* y, const char* x, int n); QString i18nc(const char* y, const char* x, const QString& s); QString i18nc(const char* y, const char* x, const QString& s1, const QString& s2); -QString i18nc(const char* y, const char* x, int n, int m){return QObject::tr(x, y).arg(n).arg(m);} -QString i18n(const char* x, int n, int m){return QObject::tr(x).arg(n).arg(m);} -QString i18n(const char* x, const QString& s1, const QString& s2){return QObject::tr(x).arg(s1).arg(s2);} -QString i18n(const char* x){return QObject::tr(x);} +QString i18nc(const char* y, const char* x, int n, int m) +{ + return QObject::tr(x, y).arg(n).arg(m); +} +QString i18n(const char* x, int n, int m) +{ + return QObject::tr(x).arg(n).arg(m); +} +QString i18n(const char* x, const QString& s1, const QString& s2) +{ + return QObject::tr(x).arg(s1).arg(s2); +} +QString i18n(const char* x) +{ + return QObject::tr(x); +} #endif #define I18N_NOOP2(y, x) x diff --git a/src/nokde-stubs/kmainwindow.h b/src/nokde-stubs/kmainwindow.h --- a/src/nokde-stubs/kmainwindow.h +++ b/src/nokde-stubs/kmainwindow.h @@ -10,15 +10,24 @@ class KMainWindow: public QMainWindow { public: - KMainWindow(QWidget* ):QMainWindow(0){setAttribute(Qt::WA_DeleteOnClose, true);} - void setCaption(const QString& s, bool m=false){Q_UNUSED(m) setWindowTitle(s);} + KMainWindow(QWidget*): QMainWindow(0) + { + setAttribute(Qt::WA_DeleteOnClose, true); + } + void setCaption(const QString& s, bool m = false) + { + Q_UNUSED(m) setWindowTitle(s); + } - virtual bool queryClose(){return true;} + virtual bool queryClose() + { + return true; + } protected: void closeEvent(QCloseEvent *event) { - event->setAccepted( queryClose() ); + event->setAccepted(queryClose()); } }; diff --git a/src/nokde-stubs/kmessagebox.h b/src/nokde-stubs/kmessagebox.h --- a/src/nokde-stubs/kmessagebox.h +++ b/src/nokde-stubs/kmessagebox.h @@ -5,52 +5,64 @@ namespace KStandardGuiItem { - static inline int save(){return 0;} - static inline int discard(){return 0;} - static inline int yes(){return 0;} - static inline int no(){return 0;} +static inline int save() +{ + return 0; +} +static inline int discard() +{ + return 0; +} +static inline int yes() +{ + return 0; +} +static inline int no() +{ + return 0; +} }; #define KGuiItem(x) 0 class KMessageBox: public QMessageBox { public: - enum {Continue=QMessageBox::Ignore}; + enum {Continue = QMessageBox::Ignore}; static QMessageBox::StandardButton warningYesNoCancel(QWidget *parent, const QString &text, - const QString &caption, - int y=0, - int n=0, - int c=0, - const QString &dontAskAgainName=QString()) + const QString &caption, + int y = 0, + int n = 0, + int c = 0, + const QString &dontAskAgainName = QString()) { Q_UNUSED(y) Q_UNUSED(n) Q_UNUSED(c) Q_UNUSED(dontAskAgainName) - return warning(parent, caption, text, Yes|No|Cancel, Yes); + return warning(parent, caption, text, Yes | No | Cancel, Yes); } static QMessageBox::StandardButton questionYesNoCancel(QWidget *parent, const QString &text, - const QString &caption, - int y=0, - int n=0, - int c=0, - const QString &dontAskAgainName=QString()) + const QString &caption, + int y = 0, + int n = 0, + int c = 0, + const QString &dontAskAgainName = QString()) { Q_UNUSED(y) Q_UNUSED(n) Q_UNUSED(c) Q_UNUSED(dontAskAgainName) - return question(parent, caption, text, Yes|No|Cancel, Yes); + return question(parent, caption, text, Yes | No | Cancel, Yes); } static QMessageBox::StandardButton questionYesNo(QWidget *parent, const QString &text, - const QString &caption, - int y=0, - int n=0, - const QString &dontAskAgainName=QString()) + const QString &caption, + int y = 0, + int n = 0, + const QString &dontAskAgainName = QString()) { Q_UNUSED(y) Q_UNUSED(n) Q_UNUSED(dontAskAgainName) - return question(parent, caption, text, Yes|No|Cancel, Yes); + return question(parent, caption, text, Yes | No | Cancel, Yes); } static void information(QWidget *parent, - const QString &text, - const QString &caption = QString(), - const QString &dontShowAgainName = QString()) + const QString &text, + const QString &caption = QString(), + const QString &dontShowAgainName = QString()) { Q_UNUSED(dontShowAgainName) QMessageBox::information(parent, caption, text); diff --git a/src/nokde-stubs/kpassivepopup.h b/src/nokde-stubs/kpassivepopup.h --- a/src/nokde-stubs/kpassivepopup.h +++ b/src/nokde-stubs/kpassivepopup.h @@ -4,10 +4,10 @@ namespace KPassivePopup { - enum {Balloon}; - void message( int, const QString &caption, const QString &text, - QWidget *parent ) - {} +enum {Balloon}; +void message(int, const QString &caption, const QString &text, + QWidget *parent) +{} }; diff --git a/src/nokde-stubs/ktextedit.h b/src/nokde-stubs/ktextedit.h --- a/src/nokde-stubs/ktextedit.h +++ b/src/nokde-stubs/ktextedit.h @@ -6,8 +6,8 @@ class KTextEdit: public QTextEdit { public: - KTextEdit(QWidget* p):QTextEdit(p){} - void setHighlighter(void*){} + KTextEdit(QWidget* p): QTextEdit(p) {} + void setHighlighter(void*) {} }; diff --git a/src/nokde-stubs/lokalizesubwindowbase.cpp b/src/nokde-stubs/lokalizesubwindowbase.cpp --- a/src/nokde-stubs/lokalizesubwindowbase.cpp +++ b/src/nokde-stubs/lokalizesubwindowbase.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -34,33 +34,33 @@ , file(m_mainWindow->menuBar()->addMenu(QApplication::translate("QMenuBar", "File"))) , edit(m_mainWindow->menuBar()->addMenu(QApplication::translate("QMenuBar", "Edit"))) , view(m_mainWindow->menuBar()->addMenu(QApplication::translate("QMenuBar", "View"))) - , go (m_mainWindow->menuBar()->addMenu(QApplication::translate("QMenuBar", "Go"))) + , go(m_mainWindow->menuBar()->addMenu(QApplication::translate("QMenuBar", "Go"))) , sync(m_mainWindow->menuBar()->addMenu(QApplication::translate("QMenuBar", "Sync"))) , tools(m_mainWindow->menuBar()->addMenu(QApplication::translate("QMenuBar", "Tools"))) - , tm (new QMenu(QApplication::translate("QMenuBar", "Translation Memory"))) + , tm(new QMenu(QApplication::translate("QMenuBar", "Translation Memory"))) , glossary(new QMenu(QApplication::translate("QMenuBar", "Glossary"))) { - QAction* a=file->addAction(QApplication::translate("QMenuBar", "Open..."), Project::instance(),SLOT(fileOpen())); + QAction* a = file->addAction(QApplication::translate("QMenuBar", "Open..."), Project::instance(), SLOT(fileOpen())); a->setShortcut(QKeySequence::Open); - a=file->addAction(QApplication::translate("QMenuBar", "Close"), m_mainWindow,SLOT(close())); + a = file->addAction(QApplication::translate("QMenuBar", "Close"), m_mainWindow, SLOT(close())); a->setShortcut(QKeySequence::Close); - QMenu* help=m_mainWindow->menuBar()->addMenu(QApplication::translate("QMenuBar", "Help")); - a=help->addAction(QApplication::translate("QMenuBar", "About Lokalize"), KAboutData::instance,SLOT(doAbout())); + QMenu* help = m_mainWindow->menuBar()->addMenu(QApplication::translate("QMenuBar", "Help")); + a = help->addAction(QApplication::translate("QMenuBar", "About Lokalize"), KAboutData::instance, SLOT(doAbout())); a->setMenuRole(QAction::AboutRole); - a=help->addAction(QApplication::translate("QMenuBar", "About Qt"), qApp,SLOT(aboutQt())); + a = help->addAction(QApplication::translate("QMenuBar", "About Qt"), qApp, SLOT(aboutQt())); a->setMenuRole(QAction::AboutQtRole); - a=tools->addAction(i18nc("@action:inmenu","Search and replace in files"),Project::instance(),SLOT(showFileSearch())); + a = tools->addAction(i18nc("@action:inmenu", "Search and replace in files"), Project::instance(), SLOT(showFileSearch())); a->setShortcut(QKeySequence::Find); - a=tools->addAction(i18nc("@action:inmenu","Find next in files"),Project::instance(),SLOT(fileSearchNext())); + a = tools->addAction(i18nc("@action:inmenu", "Find next in files"), Project::instance(), SLOT(fileSearchNext())); a->setShortcut(QKeySequence::FindNext); tools->addSeparator(); - a=tools->addAction(i18nc("@action:inmenu","Translation memory"),Project::instance(),SLOT(showTM())); + a = tools->addAction(i18nc("@action:inmenu", "Translation memory"), Project::instance(), SLOT(showTM())); a->setShortcut(Qt::Key_F7); } @@ -75,8 +75,7 @@ if (name.startsWith("show")) view->addAction(a); if (name.startsWith("tools")) tools->addAction(a); - if (name=="mergesecondary_back") - { + if (name == "mergesecondary_back") { if (!tm->isEmpty()) edit->addMenu(tm); if (!glossary->isEmpty()) edit->addMenu(glossary); } @@ -86,27 +85,25 @@ QAction* KActionCategory::addAction(KStandardAction::StandardAction t, QObject* rcv, const char* slot) { - QString name=QStringLiteral("std"); + QString name = QStringLiteral("std"); QMenu* m = 0; - QKeySequence::StandardKey k=QKeySequence::UnknownKey; - switch(t) - { - case KStandardAction::Save: name=QApplication::translate("QMenuBar","Save"); m=c->file; k=QKeySequence::Save; break; - case KStandardAction::SaveAs: name=QApplication::translate("QMenuBar","Save As...");m=c->file;k-QKeySequence::SaveAs;break; - case KStandardAction::Next: m=c->go; k=QKeySequence::MoveToNextPage; break; - case KStandardAction::Prior: m=c->go; k=QKeySequence::MoveToPreviousPage; break; - default:; + QKeySequence::StandardKey k = QKeySequence::UnknownKey; + switch (t) { + case KStandardAction::Save: name = QApplication::translate("QMenuBar", "Save"); m = c->file; k = QKeySequence::Save; break; + case KStandardAction::SaveAs: name = QApplication::translate("QMenuBar", "Save As..."); m = c->file; k - QKeySequence::SaveAs; break; + case KStandardAction::Next: m = c->go; k = QKeySequence::MoveToNextPage; break; + case KStandardAction::Prior: m = c->go; k = QKeySequence::MoveToPreviousPage; break; + default:; } - if (m) - { - QAction* a=m->addAction(name, rcv, slot); + if (m) { + QAction* a = m->addAction(name, rcv, slot); if ((int)k) a->setShortcut(k); - if (t==KStandardAction::SaveAs) + if (t == KStandardAction::SaveAs) c->file->addSeparator(); return a; } - QAction* a=new QAction(name, rcv); + QAction* a = new QAction(name, rcv); QObject::connect(a, SIGNAL(triggered(bool)), rcv, slot); return a; } diff --git a/src/nokde-stubs/prefs.h b/src/nokde-stubs/prefs.h --- a/src/nokde-stubs/prefs.h +++ b/src/nokde-stubs/prefs.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -34,21 +34,33 @@ Q_OBJECT public: - SettingsController():dirty(false), m_mainWindowPtr(0){} - ~SettingsController(){} + SettingsController(): dirty(false), m_mainWindowPtr(0) {} + ~SettingsController() {} bool dirty; - void setMainWindowPtr(QWidget* w){m_mainWindowPtr=w;} - QWidget* mainWindowPtr(){return m_mainWindowPtr;} + void setMainWindowPtr(QWidget* w) + { + m_mainWindowPtr = w; + } + QWidget* mainWindowPtr() + { + return m_mainWindowPtr; + } public slots: - void showSettingsDialog(){} + void showSettingsDialog() {} bool ensureProjectIsLoaded(); - QString projectOpen(QString path=QString(), bool doOpen=true){return QString();} - bool projectCreate(){return true;} - void projectConfigure(){} + QString projectOpen(QString path = QString(), bool doOpen = true) + { + return QString(); + } + bool projectCreate() + { + return true; + } + void projectConfigure() {} signals: void generalSettingsChanged(); diff --git a/src/nokde-stubs/prefs.cpp b/src/nokde-stubs/prefs.cpp --- a/src/nokde-stubs/prefs.cpp +++ b/src/nokde-stubs/prefs.cpp @@ -16,17 +16,17 @@ #include #include -SettingsController* SettingsController::_instance=0; +SettingsController* SettingsController::_instance = 0; void SettingsController::cleanupSettingsController() { - delete SettingsController::_instance; - SettingsController::_instance = 0; + delete SettingsController::_instance; + SettingsController::_instance = 0; } SettingsController* SettingsController::instance() { - if (_instance==0){ - _instance=new SettingsController; + if (_instance == 0) { + _instance = new SettingsController; ///qAddPostRoutine(SettingsController::cleanupSettingsController); } @@ -42,34 +42,37 @@ QString fullUserName();// defined in helpers.cpp Settings::Settings() - : mAddColor(0x99,0xCC,0xFF) - , mDelColor(0xFF,0x99,0x99) - , mMsgFont() - , mHighlightSpaces(true) - , mLeds(false) - - // Editor - , mAutoApprove(true) - , mAutoSpellcheck(true) - , mMouseWheelGo(false) - , mAltTransViewEverShownWithData(false) - - // TM - , mPrefetchTM(false) - , mAutoaddTM(true) - , mScanToTMOnOpen(false) - - , mWordCompletionLength(3) - , mSuggCount(10) + : mAddColor(0x99, 0xCC, 0xFF) + , mDelColor(0xFF, 0x99, 0x99) + , mMsgFont() + , mHighlightSpaces(true) + , mLeds(false) + + // Editor + , mAutoApprove(true) + , mAutoSpellcheck(true) + , mMouseWheelGo(false) + , mAltTransViewEverShownWithData(false) + + // TM + , mPrefetchTM(false) + , mAutoaddTM(true) + , mScanToTMOnOpen(false) + + , mWordCompletionLength(3) + , mSuggCount(10) { QSettings s; mAuthorName = s.value(QStringLiteral("Author/Name"), QString()).toString(); - if (mAuthorName.isEmpty()) {mAuthorName = fullUserName(); if (mAuthorName.length()) mAuthorName[0]=mAuthorName.at(0).toUpper();} + if (mAuthorName.isEmpty()) { + mAuthorName = fullUserName(); + if (mAuthorName.length()) mAuthorName[0] = mAuthorName.at(0).toUpper(); + } mAuthorEmail = s.value(QStringLiteral("Author/Email"), QString()).toString(); mDefaultLangCode = s.value(QStringLiteral("Editor/TargetLangCode"), QLocale::system().name()).toString(); - mAltTransViewEverShownWithData = s.value(QStringLiteral("Editor/AltTransViewEverShownWithData"),false).toBool(); + mAltTransViewEverShownWithData = s.value(QStringLiteral("Editor/AltTransViewEverShownWithData"), false).toBool(); } void Settings::save() @@ -85,21 +88,21 @@ Settings *Settings::self() { - static Settings* s=new Settings; + static Settings* s = new Settings; return s; } void writeUiState(const char* elementName, const QByteArray& state) { QSettings s; - s.setValue(QStringLiteral("UI/")+QLatin1String(elementName), state.toBase64()); + s.setValue(QStringLiteral("UI/") + QLatin1String(elementName), state.toBase64()); } QByteArray readUiState(const char* elementName) { QSettings s; - return QByteArray::fromBase64( s.value(QStringLiteral("UI/")+QLatin1String(elementName), QByteArray()).toByteArray() ); + return QByteArray::fromBase64(s.value(QStringLiteral("UI/") + QLatin1String(elementName), QByteArray()).toByteArray()); } @@ -109,22 +112,22 @@ #include "editortab.h" ProjectBase::ProjectBase() - : m_tmTab(0) - , mProjectID(QStringLiteral("default")) - , mKind() - , mTargetLangCode(Settings::defaultLangCode()) - , mSourceLangCode("en_US") - , mPoBaseDir(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)) - , mPotBaseDir() - , mBranchDir() - , mAltDir() - , mGlossaryTbx(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)+"/terms.tbx") - , mMainQA(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)+"/main.lqa") - - // RegExps - , mAccel("&") - , mMarkup("(<[^>]+>)+|(&[A-Za-z_:][A-Za-z0-9_\\.:-]*;)+") - , mWordWrap(80) + : m_tmTab(0) + , mProjectID(QStringLiteral("default")) + , mKind() + , mTargetLangCode(Settings::defaultLangCode()) + , mSourceLangCode("en_US") + , mPoBaseDir(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)) + , mPotBaseDir() + , mBranchDir() + , mAltDir() + , mGlossaryTbx(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/terms.tbx") + , mMainQA(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/main.lqa") + + // RegExps + , mAccel("&") + , mMarkup("(<[^>]+>)+|(&[A-Za-z_:][A-Za-z0-9_\\.:-]*;)+") + , mWordWrap(80) { QSettings s; mSourceLangCode = s.value(QStringLiteral("Project/SourceLangCode"), mSourceLangCode).toString(); @@ -139,8 +142,8 @@ } ProjectLocal::ProjectLocal() - : mRole(Translator) - , mFirstRun(true) + : mRole(Translator) + , mFirstRun(true) { QSettings s; mRole = s.value("Project/AuthorRole", mRole).toInt(); @@ -156,43 +159,35 @@ EditorTab* ProjectBase::fileOpen(QString filePath, int entry, bool setAsActive, const QString& mergeFile, bool silent) { - if (filePath.length()) - { - FileToEditor::const_iterator it=m_fileToEditor.constFind(filePath); - if (it!=m_fileToEditor.constEnd()) - { - qCWarning(LOKALIZE_LOG)<<"already opened:"<activateWindow(); return e; } } } - QByteArray state=m_lastEditorState; - EditorTab* w=new EditorTab(0); + QByteArray state = m_lastEditorState; + EditorTab* w = new EditorTab(0); QString suggestedDirPath; - if (EditorTab* e=qobject_cast(QApplication::activeWindow())) - { - QString fp=e->currentFilePath(); - if (fp.length()) suggestedDirPath=QFileInfo(fp).absolutePath(); + if (EditorTab* e = qobject_cast(QApplication::activeWindow())) { + QString fp = e->currentFilePath(); + if (fp.length()) suggestedDirPath = QFileInfo(fp).absolutePath(); } - if (!w->fileOpen(filePath,suggestedDirPath,silent)) - { + if (!w->fileOpen(filePath, suggestedDirPath, silent)) { w->deleteLater(); return 0; } - if (filePath.length()) - { - FileToEditor::const_iterator it=m_fileToEditor.constFind(filePath); - if (it!=m_fileToEditor.constEnd()) - { - qCWarning(LOKALIZE_LOG)<<"already opened:"<activateWindow(); w->deleteLater(); return e; @@ -212,40 +207,38 @@ w->mergeOpen(mergeFile); // m_openRecentFileAction->addUrl(QUrl::fromLocalFile(filePath));//(w->currentUrl()); - connect(w, SIGNAL(destroyed(QObject*)),this,SLOT(editorClosed(QObject*))); - connect(w, SIGNAL(fileOpenRequested(QString,QString,QString)),this,SLOT(fileOpen(QString,QString,QString))); - connect(w, SIGNAL(tmLookupRequested(QString,QString)),this,SLOT(lookupInTranslationMemory(QString,QString))); + connect(w, SIGNAL(destroyed(QObject*)), this, SLOT(editorClosed(QObject*))); + connect(w, SIGNAL(fileOpenRequested(QString, QString, QString)), this, SLOT(fileOpen(QString, QString, QString))); + connect(w, SIGNAL(tmLookupRequested(QString, QString)), this, SLOT(lookupInTranslationMemory(QString, QString))); - filePath=w->currentFilePath(); - QStringRef fnSlashed=filePath.midRef(filePath.lastIndexOf('/')); + filePath = w->currentFilePath(); + QStringRef fnSlashed = filePath.midRef(filePath.lastIndexOf('/')); FileToEditor::const_iterator i = m_fileToEditor.constBegin(); - while (i != m_fileToEditor.constEnd()) - { - if (i.key().endsWith(fnSlashed)) - { + while (i != m_fileToEditor.constEnd()) { + if (i.key().endsWith(fnSlashed)) { i.value()->setFullPathShown(true); w->setFullPathShown(true); } ++i; } - m_fileToEditor.insert(filePath,w); + m_fileToEditor.insert(filePath, w); //emit editorAdded(); return w; } EditorTab* ProjectBase::fileOpen(const QString& filePath, const QString& source, const QString& ctxt) { - EditorTab* w=fileOpen(filePath, 0, true); + EditorTab* w = fileOpen(filePath, 0, true); if (!w) return 0;//TODO message - w->findEntryBySourceContext(source,ctxt); + w->findEntryBySourceContext(source, ctxt); return w; } EditorTab* ProjectBase::fileOpen(const QString& filePath, DocPosition docPos, int selection) { - EditorTab* w=fileOpen(filePath, 0, true); + EditorTab* w = fileOpen(filePath, 0, true); if (!w) return 0;//TODO message w->gotoEntry(docPos, selection); @@ -259,8 +252,7 @@ bool ProjectBase::eventFilter(QObject *obj, QEvent *event) { - if (event->type() == QEvent::FileOpen) - { + if (event->type() == QEvent::FileOpen) { QFileOpenEvent *e = static_cast(event); fileOpen(e->file()); return true; @@ -270,36 +262,32 @@ void ProjectBase::lookupInTranslationMemory(const QString& source, const QString& target) { - TM::TMTab* w=showTM(); + TM::TMTab* w = showTM(); w->lookup(source, target); } TM::TMTab* ProjectBase::showTM() { - if (!m_tmTab) - { - m_tmTab=new TM::TMTab(0); - connect(m_tmTab, SIGNAL(fileOpenRequested(QString,QString,QString)),this,SLOT(fileOpen(QString,QString,QString))); + if (!m_tmTab) { + m_tmTab = new TM::TMTab(0); + connect(m_tmTab, SIGNAL(fileOpenRequested(QString, QString, QString)), this, SLOT(fileOpen(QString, QString, QString))); } m_tmTab->show(); m_tmTab->activateWindow(); return m_tmTab; } void ProjectBase::showFileSearch() { - if (!m_fileSearchTab) - { - m_fileSearchTab=new FileSearchTab(0); - connect(m_fileSearchTab, SIGNAL(fileOpenRequested(QString,DocPosition,int)),this,SLOT(fileOpen(QString,DocPosition,int))); - connect(m_fileSearchTab, SIGNAL(fileOpenRequested(QString)),this,SLOT(fileOpen(QString))); + if (!m_fileSearchTab) { + m_fileSearchTab = new FileSearchTab(0); + connect(m_fileSearchTab, SIGNAL(fileOpenRequested(QString, DocPosition, int)), this, SLOT(fileOpen(QString, DocPosition, int))); + connect(m_fileSearchTab, SIGNAL(fileOpenRequested(QString)), this, SLOT(fileOpen(QString))); } - if (EditorTab* e=qobject_cast(QApplication::activeWindow())) - { - QString fp=e->currentFilePath(); - if (fp.length()) - { + if (EditorTab* e = qobject_cast(QApplication::activeWindow())) { + QString fp = e->currentFilePath(); + if (fp.length()) { m_fileSearchTab->addFilesToSearch(QStringList(fp)); m_fileSearchTab->setSourceQuery(e->selectionInSource()); m_fileSearchTab->setTargetQuery(e->selectionInTarget()); @@ -320,15 +308,15 @@ -KAboutData* KAboutData::instance=0; +KAboutData* KAboutData::instance = 0; KAboutData::KAboutData(const QString&, const QString& n, const QString& v, const QString& d, KAboutLicense::L, const QString& c) - : name(n) - , version(v) - , description(d) - , copyright(c) + : name(n) + , version(v) + , description(d) + , copyright(c) { - KAboutData::instance=this; + KAboutData::instance = this; } void KAboutData::addAuthor(const QString& name, const QString&, const QString& mail) @@ -342,27 +330,26 @@ void KAboutData::addCredit(const QString& name, const QString& forwhat, const QString& mail, const QString& site) { Credit c; - c.name=name; - c.mail=mail; - c.what=forwhat; - c.site=site; + c.name = name; + c.mail = mail; + c.what = forwhat; + c.site = site; credits.append(c); } void KAboutData::doAbout() { QString cs; - foreach(const Credit& c, credits) - { - cs+=c.name%": "%c.what%"
    "; + foreach (const Credit& c, credits) { + cs += c.name % ": " % c.what % "
    "; } - QMessageBox::about(0, name, "

    "%name%' '%version%"

    "%description%"

    "%copyright.replace('\n', "
    ")%"


    Credits:
    "%cs%"
    "); + QMessageBox::about(0, name, "

    " % name % ' ' % version % "

    " % description % "

    " % copyright.replace('\n', "
    ") % "


    Credits:
    " % cs % "
    "); } namespace KLocalizedString { - void setApplicationDomain(const char*){} +void setApplicationDomain(const char*) {} }; diff --git a/src/nokde-stubs/prefs_lokalize.h b/src/nokde-stubs/prefs_lokalize.h --- a/src/nokde-stubs/prefs_lokalize.h +++ b/src/nokde-stubs/prefs_lokalize.h @@ -13,90 +13,108 @@ public: static Settings *self(); - ~Settings(){} + ~Settings() {} void save(); public slots: - static void setAuthorName(const QString& v){self()->mAuthorName = v;} - static void setAuthorEmail(const QString& v){self()->mAuthorEmail = v;} - static void setDefaultLangCode(const QString& v){self()->mDefaultLangCode = v;} + static void setAuthorName(const QString& v) + { + self()->mAuthorName = v; + } + static void setAuthorEmail(const QString& v) + { + self()->mAuthorEmail = v; + } + static void setDefaultLangCode(const QString& v) + { + self()->mDefaultLangCode = v; + } public: - static QString authorName() {return self()->mAuthorName;} - static QString authorLocalizedName() {return self()->mAuthorLocalizedName;} - static QString authorEmail() {return self()->mAuthorEmail;} + static QString authorName() + { + return self()->mAuthorName; + } + static QString authorLocalizedName() + { + return self()->mAuthorLocalizedName; + } + static QString authorEmail() + { + return self()->mAuthorEmail; + } static QString defaultLangCode() { - return self()->mDefaultLangCode; + return self()->mDefaultLangCode; } static QString defaultMailingList() { - return self()->mDefaultMailingList; + return self()->mDefaultMailingList; } static QColor addColor() { - return self()->mAddColor; + return self()->mAddColor; } static QColor delColor() { - return self()->mDelColor; + return self()->mDelColor; } static bool highlightSpaces() { - return self()->mHighlightSpaces; + return self()->mHighlightSpaces; } static QFont msgFont() { - return self()->mMsgFont; + return self()->mMsgFont; } static - void setLeds( bool v ) + void setLeds(bool v) { self()->mLeds = v; } static bool leds() { - return self()->mLeds; + return self()->mLeds; } static bool autoApprove() { - return self()->mAutoApprove; + return self()->mAutoApprove; } static - void setAutoSpellcheck( bool v ) + void setAutoSpellcheck(bool v) { self()->mAutoSpellcheck = v; } static bool autoSpellcheck() { - return self()->mAutoSpellcheck; + return self()->mAutoSpellcheck; } static bool mouseWheelGo() { - return self()->mMouseWheelGo; + return self()->mMouseWheelGo; } static @@ -106,42 +124,42 @@ } static - void setAltTransViewEverShownWithData( bool v ) + void setAltTransViewEverShownWithData(bool v) { self()->mAltTransViewEverShownWithData = v; } static int wordCompletionLength() { - return self()->mWordCompletionLength; + return self()->mWordCompletionLength; } static bool prefetchTM() { - return self()->mPrefetchTM; + return self()->mPrefetchTM; } static int suggCount() { - return self()->mSuggCount; + return self()->mSuggCount; } static bool autoaddTM() { - return self()->mAutoaddTM; + return self()->mAutoaddTM; } static bool scanToTMOnOpen() { - return self()->mScanToTMOnOpen; + return self()->mScanToTMOnOpen; } - protected: +protected: Settings(); friend class SettingsHelper; diff --git a/src/nokde-stubs/projectbase.h b/src/nokde-stubs/projectbase.h --- a/src/nokde-stubs/projectbase.h +++ b/src/nokde-stubs/projectbase.h @@ -13,20 +13,26 @@ class FileSearchTab; class EditorTab; -namespace TM{class TMTab;}; +namespace TM +{ +class TMTab; +}; class ProjectBase: public QObject { Q_OBJECT public: ProjectBase(); - ~ProjectBase(){save();} + ~ProjectBase() + { + save(); + } bool eventFilter(QObject *obj, QEvent *event); public slots: - EditorTab* fileOpen(QString url=QString(),int entry=0, bool setAsActive=true, const QString& mergeFile=QString(), bool silent=false); + EditorTab* fileOpen(QString url = QString(), int entry = 0, bool setAsActive = true, const QString& mergeFile = QString(), bool silent = false); EditorTab* fileOpen(const QString& filePath, const QString& source, const QString& ctxt); EditorTab* fileOpen(const QString& filePath, DocPosition docPos, int selection); @@ -47,67 +53,79 @@ public: - void setProjectID( const QString & v ) + void setProjectID(const QString & v) { mProjectID = v; } QString projectID() const { - return mProjectID; + return mProjectID; } - void setKind( const QString & v ) + void setKind(const QString & v) { mKind = v; } QString kind() const { - return mKind; + return mKind; } - void setLangCode( const QString & ) + void setLangCode(const QString &) { //this is called from setDefaults() //mTargetLangCode = v; } QString langCode() const { - return mTargetLangCode; + return mTargetLangCode; } public slots: - void setTargetLangCode( const QString & v ){mTargetLangCode = v;} - void setSourceLangCode( const QString & v ){mSourceLangCode = v;} + void setTargetLangCode(const QString & v) + { + mTargetLangCode = v; + } + void setSourceLangCode(const QString & v) + { + mSourceLangCode = v; + } public: - QString targetLangCode() const {return mTargetLangCode;} - QString sourceLangCode() const {return mSourceLangCode;} + QString targetLangCode() const + { + return mTargetLangCode; + } + QString sourceLangCode() const + { + return mSourceLangCode; + } - void setMailingList( const QString & v ) + void setMailingList(const QString & v) { mMailingList = v; } QString mailingList() const { - return mMailingList; + return mMailingList; } - void setPoBaseDir( const QString & v ) + void setPoBaseDir(const QString & v) { mPoBaseDir = v; } QString poBaseDir() const { - return mPoBaseDir; + return mPoBaseDir; } /** Set PotBaseDir */ - void setPotBaseDir( const QString & v ) + void setPotBaseDir(const QString & v) { mPotBaseDir = v; } @@ -117,13 +135,13 @@ */ QString potBaseDir() const { - return mPotBaseDir; + return mPotBaseDir; } /** Set BranchDir */ - void setBranchDir( const QString & v ) + void setBranchDir(const QString & v) { mBranchDir = v; } @@ -133,13 +151,13 @@ */ QString branchDir() const { - return mBranchDir; + return mBranchDir; } /** Set AltDir */ - void setAltDir( const QString & v ) + void setAltDir(const QString & v) { mAltDir = v; } @@ -149,13 +167,13 @@ */ QString altDir() const { - return mAltDir; + return mAltDir; } /** Set GlossaryTbx */ - void setGlossaryTbx( const QString & v ) + void setGlossaryTbx(const QString & v) { mGlossaryTbx = v; } @@ -165,13 +183,13 @@ */ QString glossaryTbx() const { - return mGlossaryTbx; + return mGlossaryTbx; } /** Set MainQA */ - void setMainQA( const QString & v ) + void setMainQA(const QString & v) { mMainQA = v; } @@ -181,13 +199,13 @@ */ QString mainQA() const { - return mMainQA; + return mMainQA; } /** Set Accel */ - void setAccel( const QString & v ) + void setAccel(const QString & v) { mAccel = v; } @@ -197,13 +215,13 @@ */ QString accel() const { - return mAccel; + return mAccel; } /** Set Markup */ - void setMarkup( const QString & v ) + void setMarkup(const QString & v) { mMarkup = v; } @@ -213,13 +231,13 @@ */ QString markup() const { - return mMarkup; + return mMarkup; } /** Set WordWrap */ - void setWordWrap( int v ) + void setWordWrap(int v) { mWordWrap = v; } @@ -229,12 +247,12 @@ */ int wordWrap() const { - return mWordWrap; + return mWordWrap; } void save(); - void setDefaults(){} - protected: + void setDefaults() {} +protected: // General QString mProjectID; @@ -255,7 +273,7 @@ QString mMarkup; int mWordWrap; - private: +private: }; #endif diff --git a/src/nokde-stubs/projectlocal.h b/src/nokde-stubs/projectlocal.h --- a/src/nokde-stubs/projectlocal.h +++ b/src/nokde-stubs/projectlocal.h @@ -11,30 +11,54 @@ enum PersonRole { Translator, Reviewer, Approver, Undefined }; ProjectLocal(); - ~ProjectLocal(){save();} + ~ProjectLocal() + { + save(); + } public slots: - void setRole( int v ){mRole = (PersonRole)v;} -public: - void setRole( PersonRole v ){mRole = v;} - PersonRole role() const {return static_cast(mRole);} + void setRole(int v) + { + mRole = (PersonRole)v; + } +public: + void setRole(PersonRole v) + { + mRole = v; + } + PersonRole role() const + { + return static_cast(mRole); + } - void setFirstRun( bool v ){mFirstRun = v;} - bool firstRun() const{return mFirstRun;} + void setFirstRun(bool v) + { + mFirstRun = v; + } + bool firstRun() const + { + return mFirstRun; + } - void setSourceDir( const QString& s){mSourceDir = s;} - QString sourceDir() const{return mSourceDir;} + void setSourceDir(const QString& s) + { + mSourceDir = s; + } + QString sourceDir() const + { + return mSourceDir; + } void save(); - void setDefaults(){} - protected: + void setDefaults() {} +protected: // Personal int mRole; bool mFirstRun; QString mSourceDir; - private: +private: }; #endif diff --git a/src/nokde-stubs/welcometab.h b/src/nokde-stubs/welcometab.h --- a/src/nokde-stubs/welcometab.h +++ b/src/nokde-stubs/welcometab.h @@ -44,9 +44,9 @@ //helps translate 'Russian (ru_UA)' -> 'ru_UA' class LangCodeSaver: public QObject { -Q_OBJECT + Q_OBJECT public: - LangCodeSaver(QWidget* p):QObject(p){} + LangCodeSaver(QWidget* p): QObject(p) {} public slots: void setLangCode(int index); signals: diff --git a/src/nokde-stubs/welcometab.cpp b/src/nokde-stubs/welcometab.cpp --- a/src/nokde-stubs/welcometab.cpp +++ b/src/nokde-stubs/welcometab.cpp @@ -46,15 +46,15 @@ setupUi(centralWidget()); QStringList i; - i<addItems(i); roleCombo->setCurrentIndex(Project::instance()->local()->role()); connect(roleCombo, SIGNAL(currentIndexChanged(int)), Project::instance()->local(), SLOT(setRole(int))); sourceLangCombo->setModel(LanguageListModel::instance()->sortModel()); targetLangCombo->setModel(LanguageListModel::instance()->sortModel()); - sourceLangCombo->setCurrentIndex(LanguageListModel::instance()->sortModelRowForLangCode( Project::instance()->sourceLangCode() )); - targetLangCombo->setCurrentIndex(LanguageListModel::instance()->sortModelRowForLangCode( Project::instance()->targetLangCode() )); + sourceLangCombo->setCurrentIndex(LanguageListModel::instance()->sortModelRowForLangCode(Project::instance()->sourceLangCode())); + targetLangCombo->setCurrentIndex(LanguageListModel::instance()->sortModelRowForLangCode(Project::instance()->targetLangCode())); LangCodeSaver* s = new LangCodeSaver(this); LangCodeSaver* t = new LangCodeSaver(this); connect(sourceLangCombo, SIGNAL(currentIndexChanged(int)), s, SLOT(setLangCode(int))); @@ -80,18 +80,16 @@ void WelcomeTab::dragEnterEvent(QDragEnterEvent* event) { - if(dragIsAcceptable(event->mimeData()->urls())) + if (dragIsAcceptable(event->mimeData()->urls())) event->acceptProposedAction(); } void WelcomeTab::dropEvent(QDropEvent* event) { - foreach(const QUrl& url, event->mimeData()->urls()) - { - const QString& filePath=url.toLocalFile(); + foreach (const QUrl& url, event->mimeData()->urls()) { + const QString& filePath = url.toLocalFile(); if (Catalog::extIsSupported(filePath) - && Project::instance()->fileOpen(filePath)) - { + && Project::instance()->fileOpen(filePath)) { event->acceptProposedAction(); } } diff --git a/src/noteeditor.h b/src/noteeditor.h --- a/src/noteeditor.h +++ b/src/noteeditor.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -38,14 +38,17 @@ class NoteEditor: public QWidget { -Q_OBJECT + Q_OBJECT public: NoteEditor(QWidget* parent); - ~NoteEditor(){} + ~NoteEditor() {} Note note(); void setNote(const Note&, int idx); - int noteIndex(){return m_idx;} + int noteIndex() + { + return m_idx; + } void setNoteAuthors(const QStringList&); void setFromFieldVisible(bool); @@ -66,9 +69,9 @@ class TextEdit: public QPlainTextEdit { -Q_OBJECT + Q_OBJECT public: - TextEdit(QWidget* parent): QPlainTextEdit(parent){} + TextEdit(QWidget* parent): QPlainTextEdit(parent) {} void keyPressEvent(QKeyEvent* e); signals: void accepted(); diff --git a/src/noteeditor.cpp b/src/noteeditor.cpp --- a/src/noteeditor.cpp +++ b/src/noteeditor.cpp @@ -9,7 +9,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -48,36 +48,36 @@ void TextEdit::keyPressEvent(QKeyEvent* keyEvent) { if (keyEvent->modifiers()& Qt::ControlModifier - && keyEvent->key()==Qt::Key_Return) + && keyEvent->key() == Qt::Key_Return) emit accepted(); - else if (keyEvent->key()==Qt::Key_Escape) + else if (keyEvent->key() == Qt::Key_Escape) emit rejected(); else QPlainTextEdit::keyPressEvent(keyEvent); } NoteEditor::NoteEditor(QWidget* parent) - : QWidget(parent) - , m_from(new QComboBox(this)) - , m_fromLabel(new QLabel(i18nc("@info:label","From:"),this)) - , m_authors(new QStringListModel(this)) - , m_edit(new TextEdit(this)) - , m_idx(-1) + : QWidget(parent) + , m_from(new QComboBox(this)) + , m_fromLabel(new QLabel(i18nc("@info:label", "From:"), this)) + , m_authors(new QStringListModel(this)) + , m_edit(new TextEdit(this)) + , m_idx(-1) { - setToolTip(i18nc("@info:tooltip","Save empty note to remove it")); - m_from->setToolTip(i18nc("@info:tooltip","Author of this note")); + setToolTip(i18nc("@info:tooltip", "Save empty note to remove it")); + m_from->setToolTip(i18nc("@info:tooltip", "Author of this note")); m_from->setEditable(true); m_from->setModel(m_authors); m_from->completer()->setModel(m_authors); - QVBoxLayout* main=new QVBoxLayout(this); - QHBoxLayout* prop=new QHBoxLayout; + QVBoxLayout* main = new QVBoxLayout(this); + QHBoxLayout* prop = new QHBoxLayout; main->addLayout(prop); prop->addWidget(m_fromLabel); - prop->addWidget(m_from,42); + prop->addWidget(m_from, 42); main->addWidget(m_edit); - QDialogButtonBox* box=new QDialogButtonBox(QDialogButtonBox::Save|QDialogButtonBox::Discard, this); + QDialogButtonBox* box = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Discard, this); box->button(QDialogButtonBox::Save)->setToolTip(i18n("Ctrl+Enter")); box->button(QDialogButtonBox::Discard)->setToolTip(i18n("Esc")); @@ -97,25 +97,24 @@ Note NoteEditor::note() { - m_note.content=m_edit->toPlainText(); - m_note.from=m_from->currentText(); + m_note.content = m_edit->toPlainText(); + m_note.from = m_from->currentText(); return m_note; } void NoteEditor::setNote(const Note& note, int idx) { - m_note=note; + m_note = note; m_edit->setPlainText(note.content); - QString from=note.from; - if (from.isEmpty()) from=Settings::authorName(); + QString from = note.from; + if (from.isEmpty()) from = Settings::authorName(); m_from->setCurrentText(from); - QStringList l=m_authors->stringList(); - if (!l.contains(from)) - { + QStringList l = m_authors->stringList(); + if (!l.contains(from)) { l.append(from); m_authors->setStringList(l); } - m_idx=idx; + m_idx = idx; m_edit->setFocus(); } @@ -126,34 +125,31 @@ int displayNotes(QTextBrowser* browser, const QVector< Note >& notes, int active, bool multiple) { - QTextCursor t=browser->textCursor(); + QTextCursor t = browser->textCursor(); t.movePosition(QTextCursor::End); - int realOffset=0; - - static const QString BR=QStringLiteral("
    "); - if (!notes.isEmpty()) - { - t.insertHtml(i18nc("@info XLIFF notes representation","Notes:")+BR); - int i=0; - foreach(const Note& note, notes) - { + int realOffset = 0; + + static const QString BR = QStringLiteral("
    "); + if (!notes.isEmpty()) { + t.insertHtml(i18nc("@info XLIFF notes representation", "Notes:") + BR); + int i = 0; + foreach (const Note& note, notes) { if (!note.from.isEmpty()) - t.insertHtml(QStringLiteral("")%note.from%QStringLiteral(": ")); - - if (i==active) - realOffset=t.position(); - QString content=escapeWithLinks(note.content); - if (!multiple && content.contains('\n')) content+='\n'; - content.replace('\n',BR); - content+=QString(QStringLiteral(" (")).arg(i)%i18nc("link to edit note","edit...")%QStringLiteral(")
    "); + t.insertHtml(QStringLiteral("") % note.from % QStringLiteral(": ")); + + if (i == active) + realOffset = t.position(); + QString content = escapeWithLinks(note.content); + if (!multiple && content.contains('\n')) content += '\n'; + content.replace('\n', BR); + content += QString(QStringLiteral(" (")).arg(i) % i18nc("link to edit note", "edit...") % QStringLiteral(")
    "); t.insertHtml(content); i++; } if (multiple) - t.insertHtml(QStringLiteral("")%i18nc("link to add a note","Add...")%QStringLiteral(" ")); - } - else - browser->insertHtml(QStringLiteral("")%i18nc("link to add a note","Add a note...")%QStringLiteral(" ")); + t.insertHtml(QStringLiteral("") % i18nc("link to add a note", "Add...") % QStringLiteral(" ")); + } else + browser->insertHtml(QStringLiteral("") % i18nc("link to add a note", "Add a note...") % QStringLiteral(" ")); return realOffset; } diff --git a/src/phaseswindow.h b/src/phaseswindow.h --- a/src/phaseswindow.h +++ b/src/phaseswindow.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -42,10 +42,10 @@ class MyTreeView; class PhasesWindow: public QDialog { -Q_OBJECT + Q_OBJECT public: PhasesWindow(Catalog* catalog, QWidget *parent); - ~PhasesWindow(){} + ~PhasesWindow() {} private slots: void displayPhaseNotes(const QModelIndex& current); @@ -73,15 +73,18 @@ class MyTreeView: public QTreeView { -Q_OBJECT + Q_OBJECT public: - MyTreeView(QWidget* parent):QTreeView(parent){} - ~MyTreeView(){} + MyTreeView(QWidget* parent): QTreeView(parent) {} + ~MyTreeView() {} signals: void currentIndexChanged(const QModelIndex& current); private: - void currentChanged(const QModelIndex& current, const QModelIndex&){emit currentIndexChanged(current);} + void currentChanged(const QModelIndex& current, const QModelIndex&) + { + emit currentIndexChanged(current); + } }; diff --git a/src/phaseswindow.cpp b/src/phaseswindow.cpp --- a/src/phaseswindow.cpp +++ b/src/phaseswindow.cpp @@ -51,32 +51,38 @@ class PhasesModel: public QAbstractListModel { public: - enum PhasesModelColumns - { - Date=0, + enum PhasesModelColumns { + Date = 0, Process, Company, Contact, ToolName, ColumnCount }; PhasesModel(Catalog* catalog, QObject* parent); - ~PhasesModel(){} + ~PhasesModel() {} QModelIndex addPhase(const Phase& phase); - QModelIndex activePhaseIndex()const{return index(m_activePhase);} + QModelIndex activePhaseIndex()const + { + return index(m_activePhase); + } QList addedPhases()const; - int rowCount(const QModelIndex& parent=QModelIndex()) const; - int columnCount(const QModelIndex& parent=QModelIndex()) const{Q_UNUSED(parent); return ColumnCount;} - QVariant data(const QModelIndex&,int role=Qt::DisplayRole) const; - QVariant headerData(int section, Qt::Orientation, int role=Qt::DisplayRole) const; + int rowCount(const QModelIndex& parent = QModelIndex()) const; + int columnCount(const QModelIndex& parent = QModelIndex()) const + { + Q_UNUSED(parent); + return ColumnCount; + } + QVariant data(const QModelIndex&, int role = Qt::DisplayRole) const; + QVariant headerData(int section, Qt::Orientation, int role = Qt::DisplayRole) const; private: Catalog* m_catalog; QList m_phases; - QMap m_tools; + QMap m_tools; int m_activePhase; }; @@ -86,24 +92,24 @@ , m_phases(catalog->allPhases()) , m_tools(catalog->allTools()) { - m_activePhase=m_phases.size(); - while (--m_activePhase>=0 && m_phases.at(m_activePhase).name!=catalog->activePhase()) + m_activePhase = m_phases.size(); + while (--m_activePhase >= 0 && m_phases.at(m_activePhase).name != catalog->activePhase()) ; } QModelIndex PhasesModel::addPhase(const Phase& phase) { - m_activePhase=m_phases.size(); - beginInsertRows(QModelIndex(),m_activePhase,m_activePhase); + m_activePhase = m_phases.size(); + beginInsertRows(QModelIndex(), m_activePhase, m_activePhase); m_phases.append(phase); endInsertRows(); return index(m_activePhase); } QList PhasesModel::addedPhases()const { QList result; - for (int i=m_catalog->allPhases().size();iallPhases().size(); i < m_phases.size(); ++i) result.append(m_phases.at(i)); return result; @@ -118,43 +124,40 @@ QVariant PhasesModel::data(const QModelIndex& index, int role) const { - if (role==Qt::FontRole && index.row()==m_activePhase) - { - QFont font=QApplication::font(); + if (role == Qt::FontRole && index.row() == m_activePhase) { + QFont font = QApplication::font(); font.setBold(true); return font; } - if (role==Qt::UserRole) + if (role == Qt::UserRole) return m_phases.at(index.row()).name; - if (role!=Qt::DisplayRole) + if (role != Qt::DisplayRole) return QVariant(); - const Phase& phase=m_phases.at(index.row()); - switch (index.column()) - { - case Date: return phase.date.toString(); - case Process: return phase.process; - case Company: return phase.company; - case Contact: return QString(phase.contact - %(phase.email.isEmpty()?QString():QStringLiteral(" <%1> ").arg(phase.email)) - %(phase.phone.isEmpty()?QString():QStringLiteral(", %1").arg(phase.phone))); - case ToolName: return m_tools.value(phase.tool).name; + const Phase& phase = m_phases.at(index.row()); + switch (index.column()) { + case Date: return phase.date.toString(); + case Process: return phase.process; + case Company: return phase.company; + case Contact: return QString(phase.contact + % (phase.email.isEmpty() ? QString() : QStringLiteral(" <%1> ").arg(phase.email)) + % (phase.phone.isEmpty() ? QString() : QStringLiteral(", %1").arg(phase.phone))); + case ToolName: return m_tools.value(phase.tool).name; } return QVariant(); } QVariant PhasesModel::headerData(int section, Qt::Orientation, int role) const { - if (role!=Qt::DisplayRole) + if (role != Qt::DisplayRole) return QVariant(); - switch (section) - { - case Date: return i18nc("@title:column","Date"); - case Process: return i18nc("@title:column","Process"); - case Company: return i18nc("@title:column","Company"); - case Contact: return i18nc("@title:column","Person"); - case ToolName: return i18nc("@title:column","Tool"); + switch (section) { + case Date: return i18nc("@title:column", "Date"); + case Process: return i18nc("@title:column", "Process"); + case Company: return i18nc("@title:column", "Company"); + case Contact: return i18nc("@title:column", "Person"); + case ToolName: return i18nc("@title:column", "Tool"); } return QVariant(); } @@ -166,7 +169,7 @@ { public: PhaseEditDialog(QWidget *parent); - ~PhaseEditDialog(){} + ~PhaseEditDialog() {} Phase phase()const; ProjectLocal::PersonRole role()const; @@ -180,22 +183,22 @@ , m_process(new KComboBox(this)) { QStringList processes; - processes<setModel(new QStringListModel(processes, this)); - QFormLayout* l=new QFormLayout(this); + QFormLayout* l = new QFormLayout(this); l->addRow(i18nc("noun", "Process (this will also change your role):"), m_process); - QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, this); + QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this); connect(buttonBox, &QDialogButtonBox::accepted, this, &PhaseEditDialog::accept); connect(buttonBox, &QDialogButtonBox::rejected, this, &PhaseEditDialog::reject); l->addRow(buttonBox); } Phase PhaseEditDialog::phase() const { Phase phase; - phase.process=processes()[m_process->currentIndex()]; + phase.process = processes()[m_process->currentIndex()]; return phase; } @@ -206,20 +209,20 @@ PhasesWindow::PhasesWindow(Catalog* catalog, QWidget *parent) - : QDialog(parent) - , m_catalog(catalog) - , m_model(new PhasesModel(catalog, this)) - , m_view(new MyTreeView(this)) - , m_browser(new QTextBrowser(this)) - , m_editor(0) + : QDialog(parent) + , m_catalog(catalog) + , m_model(new PhasesModel(catalog, this)) + , m_view(new MyTreeView(this)) + , m_browser(new QTextBrowser(this)) + , m_editor(0) { connect(this, &PhasesWindow::accepted, this, &PhasesWindow::handleResult); //setAttribute(Qt::WA_DeleteOnClose, true); - QVBoxLayout* l=new QVBoxLayout(this); - QHBoxLayout* btns=new QHBoxLayout; + QVBoxLayout* l = new QVBoxLayout(this); + QHBoxLayout* btns = new QHBoxLayout; l->addLayout(btns); - QPushButton* add=new QPushButton(this); + QPushButton* add = new QPushButton(this); #ifndef NOKDE KGuiItem::assign(add, KStandardGuiItem::add()); #else @@ -229,27 +232,27 @@ btns->addWidget(add); btns->addStretch(5); - QSplitter* splitter=new QSplitter(this); + QSplitter* splitter = new QSplitter(this); l->addWidget(splitter); - m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, this); + m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this); connect(m_buttonBox, &QDialogButtonBox::accepted, this, &PhasesWindow::accept); connect(m_buttonBox, &QDialogButtonBox::rejected, this, &PhasesWindow::reject); l->addWidget(m_buttonBox); m_view->setRootIsDecorated(false); m_view->setModel(m_model); splitter->addWidget(m_view); - int column=m_model->columnCount(); - while (--column>=0) + int column = m_model->columnCount(); + while (--column >= 0) m_view->resizeColumnToContents(column); if (m_model->rowCount()) m_view->setCurrentIndex(m_model->activePhaseIndex()); connect(m_view, &MyTreeView::currentIndexChanged, this, &PhasesWindow::displayPhaseNotes); - m_noteView=new QWidget(this); + m_noteView = new QWidget(this); m_noteView->hide(); splitter->addWidget(m_noteView); m_stackedLayout = new QStackedLayout(m_noteView); @@ -259,26 +262,25 @@ m_browser->setOpenLinks(false); connect(m_browser, &QTextBrowser::anchorClicked, this, &PhasesWindow::anchorClicked); - splitter->setStretchFactor(0,15); - splitter->setStretchFactor(1,5); - resize(QSize(700,400)); + splitter->setStretchFactor(0, 15); + splitter->setStretchFactor(1, 5); + resize(QSize(700, 400)); } void PhasesWindow::handleResult() { m_catalog->beginMacro(i18nc("@item Undo action item", "Edit phases")); Phase last; - foreach(const Phase& phase, m_model->addedPhases()) - static_cast(m_catalog)->push(new UpdatePhaseCmd(m_catalog, last=phase)); + foreach (const Phase& phase, m_model->addedPhases()) + static_cast(m_catalog)->push(new UpdatePhaseCmd(m_catalog, last = phase)); Project::instance()->local()->setRole(roleForProcess(last.process)); - m_catalog->setActivePhase(last.name,roleForProcess(last.process)); + m_catalog->setActivePhase(last.name, roleForProcess(last.process)); QMapIterator > i(m_phaseNotes); - while (i.hasNext()) - { + while (i.hasNext()) { i.next(); - m_catalog->setPhaseNotes(i.key(),i.value()); + m_catalog->setPhaseNotes(i.key(), i.value()); } m_catalog->endMacro(); @@ -290,7 +292,7 @@ if (!d.exec()) return; - Phase phase=d.phase(); + Phase phase = d.phase(); initPhaseForCatalog(m_catalog, phase, ForceAdd); m_view->setCurrentIndex(m_model->addPhase(phase)); m_phaseNotes.insert(phase.name, QVector()); @@ -305,44 +307,41 @@ void PhasesWindow::anchorClicked(QUrl link) { - QString path=link.path().mid(1);// minus '/' + QString path = link.path().mid(1); // minus '/' - if (link.scheme()==QLatin1String("note")) - { - if (!m_editor) - { - m_editor=new NoteEditor(this); + if (link.scheme() == QLatin1String("note")) { + if (!m_editor) { + m_editor = new NoteEditor(this); m_stackedLayout->addWidget(m_editor); connect(m_editor, &NoteEditor::accepted, this, &PhasesWindow::noteEditAccepted); connect(m_editor, &NoteEditor::rejected, this, &PhasesWindow::noteEditRejected); } m_editor->setNoteAuthors(m_catalog->noteAuthors()); if (path.endsWith(QLatin1String("add"))) - m_editor->setNote(Note(),-1); - else - { - int pos=path.toInt(); - QString phaseName=phaseNameFromView(m_view); - QVector notes=m_phaseNotes.contains(phaseName)? - m_phaseNotes.value(phaseName) - :m_catalog->phaseNotes(phaseName); - m_editor->setNote(notes.at(pos),pos); + m_editor->setNote(Note(), -1); + else { + int pos = path.toInt(); + QString phaseName = phaseNameFromView(m_view); + QVector notes = m_phaseNotes.contains(phaseName) ? + m_phaseNotes.value(phaseName) + : m_catalog->phaseNotes(phaseName); + m_editor->setNote(notes.at(pos), pos); } m_stackedLayout->setCurrentIndex(1); } } void PhasesWindow::noteEditAccepted() { - QString phaseName=phaseNameFromView(m_view); + QString phaseName = phaseNameFromView(m_view); if (!m_phaseNotes.contains(phaseName)) m_phaseNotes.insert(phaseName, m_catalog->phaseNotes(phaseName)); //QVector notes=m_phaseNotes.value(phaseName); - if (m_editor->noteIndex()==-1) + if (m_editor->noteIndex() == -1) m_phaseNotes[phaseName].append(m_editor->note()); else - m_phaseNotes[phaseName][m_editor->noteIndex()]=m_editor->note(); + m_phaseNotes[phaseName][m_editor->noteIndex()] = m_editor->note(); m_stackedLayout->setCurrentIndex(0); displayPhaseNotes(m_view->currentIndex()); @@ -356,10 +355,10 @@ void PhasesWindow::displayPhaseNotes(const QModelIndex& current) { m_browser->clear(); - QString phaseName=current.data(Qt::UserRole).toString(); - QVector notes=m_phaseNotes.contains(phaseName)? - m_phaseNotes.value(phaseName) - :m_catalog->phaseNotes(phaseName); + QString phaseName = current.data(Qt::UserRole).toString(); + QVector notes = m_phaseNotes.contains(phaseName) ? + m_phaseNotes.value(phaseName) + : m_catalog->phaseNotes(phaseName); displayNotes(m_browser, notes); m_noteView->show(); m_stackedLayout->setCurrentIndex(0); diff --git a/src/prefs/prefs.h b/src/prefs/prefs.h --- a/src/prefs/prefs.h +++ b/src/prefs/prefs.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -27,7 +27,10 @@ #include class KEditListWidget; -namespace Kross {class ActionCollectionView;} +namespace Kross +{ +class ActionCollectionView; +} /** * Singleton that manages cfgs for Lokalize and projects @@ -42,14 +45,20 @@ bool dirty; - void setMainWindowPtr(QWidget* w){m_mainWindowPtr=w;} - QWidget* mainWindowPtr(){return m_mainWindowPtr;} + void setMainWindowPtr(QWidget* w) + { + m_mainWindowPtr = w; + } + QWidget* mainWindowPtr() + { + return m_mainWindowPtr; + } public slots: void showSettingsDialog(); bool ensureProjectIsLoaded(); - QString projectOpen(QString path=QString(), bool doOpen=true); + QString projectOpen(QString path = QString(), bool doOpen = true); bool projectCreate(); void projectConfigure(); @@ -79,9 +88,9 @@ */ class RelPathSaver: public QLineEdit { -Q_OBJECT + Q_OBJECT public: - RelPathSaver(QWidget* p):QLineEdit(p){} + RelPathSaver(QWidget* p): QLineEdit(p) {} public slots: void setText(const QString&); }; @@ -93,17 +102,17 @@ */ class LangCodeSaver: public QLineEdit { -Q_OBJECT + Q_OBJECT public: - LangCodeSaver(QWidget* p):QLineEdit(p){} + LangCodeSaver(QWidget* p): QLineEdit(p) {} public slots: void setLangCode(int); }; #include class ScriptsView: public Kross::ActionCollectionView { -Q_OBJECT + Q_OBJECT public: ScriptsView(QWidget* parent); diff --git a/src/prefs/prefs.cpp b/src/prefs/prefs.cpp --- a/src/prefs/prefs.cpp +++ b/src/prefs/prefs.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -59,17 +59,17 @@ //#include -SettingsController* SettingsController::_instance=0; +SettingsController* SettingsController::_instance = 0; void SettingsController::cleanupSettingsController() { - delete SettingsController::_instance; - SettingsController::_instance = 0; + delete SettingsController::_instance; + SettingsController::_instance = 0; } SettingsController* SettingsController::instance() { - if (_instance==0){ - _instance=new SettingsController; + if (_instance == 0) { + _instance = new SettingsController; qAddPostRoutine(SettingsController::cleanupSettingsController); } @@ -104,43 +104,43 @@ KConfigGroup grp = Settings::self()->config()->group("Identity"); ui_prefs_identity.DefaultLangCode->setModel(LanguageListModel::instance()->sortModel()); - ui_prefs_identity.DefaultLangCode->setCurrentIndex(LanguageListModel::instance()->sortModelRowForLangCode( grp.readEntry("DefaultLangCode", - QLocale::system().name()) )); + ui_prefs_identity.DefaultLangCode->setCurrentIndex(LanguageListModel::instance()->sortModelRowForLangCode(grp.readEntry("DefaultLangCode", + QLocale::system().name()))); connect(ui_prefs_identity.DefaultLangCode, QOverload::of(&KComboBox::activated), ui_prefs_identity.kcfg_DefaultLangCode, &LangCodeSaver::setLangCode); ui_prefs_identity.kcfg_DefaultLangCode->hide(); - dialog->addPage(w, i18nc("@title:tab","Identity"), "preferences-desktop-user"); + dialog->addPage(w, i18nc("@title:tab", "Identity"), "preferences-desktop-user"); //Editor w = new QWidget(dialog); Ui_prefs_editor ui_prefs_editor; ui_prefs_editor.setupUi(w); - dialog->addPage(w, i18nc("@title:tab","Editing"), "accessories-text-editor"); + dialog->addPage(w, i18nc("@title:tab", "Editing"), "accessories-text-editor"); //Font w = new QWidget(dialog); Ui_prefs_appearance ui_prefs_appearance; ui_prefs_appearance.setupUi(w); - dialog->addPage(w, i18nc("@title:tab","Appearance"), "preferences-desktop-font"); + dialog->addPage(w, i18nc("@title:tab", "Appearance"), "preferences-desktop-font"); //TM w = new QWidget(dialog); Ui_prefs_tm ui_prefs_tm; ui_prefs_tm.setupUi(w); - dialog->addPage(w, i18nc("@title:tab","Translation Memory"), "configure"); + dialog->addPage(w, i18nc("@title:tab", "Translation Memory"), "configure"); connect(dialog, &KConfigDialog::settingsChanged, this, &SettingsController::generalSettingsChanged); //Spellcheck #if 0 - w = new Sonnet::ConfigWidget(Settings::self()->config(),dialog); + w = new Sonnet::ConfigWidget(Settings::self()->config(), dialog); w->setParent(this); - dialog->addPage(w, i18nc("@title:tab","Spellcheck"), "spellcheck_setting"); - connect(dialog,SIGNAL(okClicked()),w,SLOT(save())); - connect(dialog,SIGNAL(applyClicked()),w,SLOT(save())); - connect(dialog,SIGNAL(defaultClicked()),w,SLOT(slotDefault())); + dialog->addPage(w, i18nc("@title:tab", "Spellcheck"), "spellcheck_setting"); + connect(dialog, SIGNAL(okClicked()), w, SLOT(save())); + connect(dialog, SIGNAL(applyClicked()), w, SLOT(save())); + connect(dialog, SIGNAL(defaultClicked()), w, SLOT(slotDefault())); #endif @@ -159,7 +159,7 @@ -ScriptsView::ScriptsView(QWidget* parent):Kross::ActionCollectionView(parent) +ScriptsView::ScriptsView(QWidget* parent): Kross::ActionCollectionView(parent) { setAcceptDrops(true); } @@ -172,8 +172,8 @@ void ScriptsView::dropEvent(QDropEvent* event) { - Kross::ActionCollectionModel* scriptsModel=static_cast(model()); - foreach(const QUrl& url, event->mimeData()->urls()) + Kross::ActionCollectionModel* scriptsModel = static_cast(model()); + foreach (const QUrl& url, event->mimeData()->urls()) if (url.path().endsWith(".rc")) scriptsModel->rootCollection()->readXmlFile(url.path()); } @@ -183,24 +183,23 @@ if (Project::instance()->isLoaded()) return true; - int answer=KMessageBox::questionYesNoCancel(m_mainWindowPtr, i18n("You have accessed a feature that requires a project to be loaded. Do you want to create a new project or open an existing project?"), - QString(), KGuiItem(i18nc("@action","New"),QIcon::fromTheme("document-new")), KGuiItem(i18nc("@action","Open"),QIcon::fromTheme("project-open")) - ); - if (answer==KMessageBox::Yes) + int answer = KMessageBox::questionYesNoCancel(m_mainWindowPtr, i18n("You have accessed a feature that requires a project to be loaded. Do you want to create a new project or open an existing project?"), + QString(), KGuiItem(i18nc("@action", "New"), QIcon::fromTheme("document-new")), KGuiItem(i18nc("@action", "Open"), QIcon::fromTheme("project-open")) + ); + if (answer == KMessageBox::Yes) return projectCreate(); - if (answer==KMessageBox::No) + if (answer == KMessageBox::No) return !projectOpen().isEmpty(); return false; } QString SettingsController::projectOpen(QString path, bool doOpen) { - if (path.isEmpty()) - { + if (path.isEmpty()) { //Project::instance()->model()->weaver()->suspend(); //KDE5PORT mutex if needed - path=QFileDialog::getOpenFileName(m_mainWindowPtr, QString(), QDir::homePath()/*_catalog->url().directory()*/, - i18n("Lokalize translation project (*.lokalize)")/*"text/x-lokalize-project"*/); + path = QFileDialog::getOpenFileName(m_mainWindowPtr, QString(), QDir::homePath()/*_catalog->url().directory()*/, + i18n("Lokalize translation project (*.lokalize)")/*"text/x-lokalize-project"*/); //Project::instance()->model()->weaver()->resume(); } @@ -214,25 +213,24 @@ { //Project::instance()->model()->weaver()->suspend(); //KDE5PORT mutex if needed - QString desirablePath=Project::instance()->desirablePath(); + QString desirablePath = Project::instance()->desirablePath(); if (desirablePath.isEmpty()) - desirablePath=QDir::homePath()+"/index.lokalize"; - QString path=QFileDialog::getSaveFileName(m_mainWindowPtr, i18nc("@window:title", "Select folder with Gettext .po files to translate"), desirablePath, i18n("Lokalize translation project (*.lokalize)") /*"text/x-lokalize-project"*/); + desirablePath = QDir::homePath() + "/index.lokalize"; + QString path = QFileDialog::getSaveFileName(m_mainWindowPtr, i18nc("@window:title", "Select folder with Gettext .po files to translate"), desirablePath, i18n("Lokalize translation project (*.lokalize)") /*"text/x-lokalize-project"*/); //Project::instance()->model()->weaver()->resume(); if (path.isEmpty()) return false; - if (m_projectActionsView && m_projectActionsView->model()) - { + if (m_projectActionsView && m_projectActionsView->model()) { //ActionCollectionModel is known to be have bad for the usecase of reinitializing krossplugin m_projectActionsView->model()->deleteLater(); m_projectActionsView->setModel(0); } //TODO ask-n-save - QDir projectFolder=QFileInfo(path).absoluteDir(); - QString projectId=projectFolder.dirName(); - if (projectFolder.cdUp()) projectId=projectFolder.dirName()%'-'%projectId;; + QDir projectFolder = QFileInfo(path).absoluteDir(); + QString projectId = projectFolder.dirName(); + if (projectFolder.cdUp()) projectId = projectFolder.dirName() % '-' % projectId;; Project::instance()->load(path, QString(), projectId); //Project::instance()->setDefaults(); //NOTE will this be an obstacle? //Project::instance()->setProjectID(); @@ -243,17 +241,15 @@ void SettingsController::projectConfigure() { - if (Project::instance()->path().isEmpty()) - { + if (Project::instance()->path().isEmpty()) { KMessageBox::error(mainWindowPtr(), i18n("Create software or OpenDocument translation project first.")); return; } - if (KConfigDialog::showDialog("project_settings")) - { + if (KConfigDialog::showDialog("project_settings")) { if (!m_projectActionsView->model()) - m_projectActionsView->setModel(new Kross::ActionCollectionModel(m_projectActionsView,Kross::Manager::self().actionCollection()->collection(Project::instance()->kind()))); + m_projectActionsView->setModel(new Kross::ActionCollectionModel(m_projectActionsView, Kross::Manager::self().actionCollection()->collection(Project::instance()->kind()))); return; } @@ -265,19 +261,19 @@ QWidget *w = new QWidget(dialog); Ui_prefs_projectmain ui_prefs_projectmain; ui_prefs_projectmain.setupUi(w); - dialog->addPage(w, i18nc("@title:tab","General"), "preferences-desktop-locale"); + dialog->addPage(w, i18nc("@title:tab", "General"), "preferences-desktop-locale"); ui_prefs_projectmain.kcfg_LangCode->hide(); ui_prefs_projectmain.kcfg_PoBaseDir->hide(); ui_prefs_projectmain.kcfg_GlossaryTbx->hide(); - Project& p=*(Project::instance()); + Project& p = *(Project::instance()); ui_prefs_projectmain.LangCode->setModel(LanguageListModel::instance()->sortModel()); ui_prefs_projectmain.LangCode->setCurrentIndex(LanguageListModel::instance()->sortModelRowForLangCode(p.langCode())); connect(ui_prefs_projectmain.LangCode, QOverload::of(&KComboBox::activated), ui_prefs_projectmain.kcfg_LangCode, &LangCodeSaver::setLangCode); - ui_prefs_projectmain.poBaseDir->setMode(KFile::Directory|KFile::ExistingOnly|KFile::LocalOnly); - ui_prefs_projectmain.glossaryTbx->setMode(KFile::File|KFile::ExistingOnly|KFile::LocalOnly); + ui_prefs_projectmain.poBaseDir->setMode(KFile::Directory | KFile::ExistingOnly | KFile::LocalOnly); + ui_prefs_projectmain.glossaryTbx->setMode(KFile::File | KFile::ExistingOnly | KFile::LocalOnly); ui_prefs_projectmain.glossaryTbx->setFilter("*.tbx\n*.xml"); connect(ui_prefs_projectmain.poBaseDir, &KUrlRequester::textChanged, ui_prefs_projectmain.kcfg_PoBaseDir, &RelPathSaver::setText); connect(ui_prefs_projectmain.glossaryTbx, &KUrlRequester::textChanged, ui_prefs_projectmain.kcfg_GlossaryTbx, &RelPathSaver::setText); @@ -295,16 +291,16 @@ ui_project_advanced.kcfg_PotBaseDir->hide(); ui_project_advanced.kcfg_BranchDir->hide(); ui_project_advanced.kcfg_AltDir->hide(); - ui_project_advanced.potBaseDir->setMode(KFile::Directory|KFile::ExistingOnly|KFile::LocalOnly); - ui_project_advanced.branchDir->setMode(KFile::Directory|KFile::ExistingOnly|KFile::LocalOnly); - ui_project_advanced.altDir->setMode(KFile::Directory|KFile::ExistingOnly|KFile::LocalOnly); + ui_project_advanced.potBaseDir->setMode(KFile::Directory | KFile::ExistingOnly | KFile::LocalOnly); + ui_project_advanced.branchDir->setMode(KFile::Directory | KFile::ExistingOnly | KFile::LocalOnly); + ui_project_advanced.altDir->setMode(KFile::Directory | KFile::ExistingOnly | KFile::LocalOnly); connect(ui_project_advanced.potBaseDir, &KUrlRequester::textChanged, ui_project_advanced.kcfg_PotBaseDir, &RelPathSaver::setText); connect(ui_project_advanced.branchDir, &KUrlRequester::textChanged, ui_project_advanced.kcfg_BranchDir, &RelPathSaver::setText); connect(ui_project_advanced.altDir, &KUrlRequester::textChanged, ui_project_advanced.kcfg_AltDir, &RelPathSaver::setText); ui_project_advanced.potBaseDir->setUrl(QUrl::fromLocalFile(p.potDir())); ui_project_advanced.branchDir->setUrl(QUrl::fromLocalFile(p.branchDir())); ui_project_advanced.altDir->setUrl(QUrl::fromLocalFile(p.altTransDir())); - dialog->addPage(w, i18nc("@title:tab","Advanced"), "applications-development-translation"); + dialog->addPage(w, i18nc("@title:tab", "Advanced"), "applications-development-translation"); //Scripts w = new QWidget(dialog); @@ -314,22 +310,22 @@ //m_projectActionsEditor=new Kross::ActionCollectionEditor(Kross::Manager::self().actionCollection()->collection(Project::instance()->projectID()),w); - m_projectActionsView=new ScriptsView(w); + m_projectActionsView = new ScriptsView(w); layout->addWidget(m_projectActionsView); - m_projectActionsView->setModel(new Kross::ActionCollectionModel(w,Kross::Manager::self().actionCollection()->collection(Project::instance()->kind()))); + m_projectActionsView->setModel(new Kross::ActionCollectionModel(w, Kross::Manager::self().actionCollection()->collection(Project::instance()->kind()))); QHBoxLayout* btns = new QHBoxLayout(); layout->addLayout(btns); btns->addWidget(m_projectActionsView->createButton(w, "edit")); - dialog->addPage(w, i18nc("@title:tab","Scripts"), "preferences-system-windows-actions"); + dialog->addPage(w, i18nc("@title:tab", "Scripts"), "preferences-system-windows-actions"); w = new QWidget(dialog); Ui_prefs_project_local ui_prefs_project_local; ui_prefs_project_local.setupUi(w); - dialog->addPage(w, Project::local(), i18nc("@title:tab","Personal"), "preferences-desktop-user"); + dialog->addPage(w, Project::local(), i18nc("@title:tab", "Personal"), "preferences-desktop-user"); connect(dialog, &KConfigDialog::settingsChanged, Project::instance(), &Project::reinit); connect(dialog, &KConfigDialog::settingsChanged, Project::instance(), &Project::save, Qt::QueuedConnection); @@ -350,35 +346,35 @@ //m_scriptsRelPrefWidget->clear(); QStringList actionz(m_scriptsPrefWidget->items()); QString projectDir(Project::instance()->projectDir()); - int i=actionz.size(); - while(--i>=0) - actionz[i]=QDir(projectDir).relativeFilePath(actionz.at(i)); + int i = actionz.size(); + while (--i >= 0) + actionz[i] = QDir(projectDir).relativeFilePath(actionz.at(i)); m_scriptsRelPrefWidget->setItems(actionz); } void LangCodeSaver::setLangCode(int index) { setText(LanguageListModel::instance()->langCodeForSortModelRow(index)); } -void RelPathSaver::setText (const QString& txt) +void RelPathSaver::setText(const QString& txt) { QLineEdit::setText(QDir(Project::instance()->projectDir()).relativeFilePath(txt)); } void writeUiState(const char* elementName, const QByteArray& state) { KConfig config; - KConfigGroup cg(&config,"MainWindow"); - cg.writeEntry(elementName,state.toBase64()); + KConfigGroup cg(&config, "MainWindow"); + cg.writeEntry(elementName, state.toBase64()); } QByteArray readUiState(const char* elementName) { KConfig config; - KConfigGroup cg(&config,"MainWindow"); - return QByteArray::fromBase64( cg.readEntry(elementName, QByteArray()) ); + KConfigGroup cg(&config, "MainWindow"); + return QByteArray::fromBase64(cg.readEntry(elementName, QByteArray())); } diff --git a/src/project/poextractor.h b/src/project/poextractor.h --- a/src/project/poextractor.h +++ b/src/project/poextractor.h @@ -40,7 +40,8 @@ enum PoState {COMMENT, MSGCTXT, MSGID, MSGID_PLURAL, MSGSTR, MSGSTR_PLURAL, - WHITESPACE, ERROR}; + WHITESPACE, ERROR + }; PoState state; int messages; int untranslated; diff --git a/src/project/poextractor.cpp b/src/project/poextractor.cpp --- a/src/project/poextractor.cpp +++ b/src/project/poextractor.cpp @@ -26,20 +26,20 @@ #include POExtractor::POExtractor() - : state(WHITESPACE) - , messages(0) - , untranslated(0) - , fuzzy(0) - , isFuzzy(false) - , isTranslated(false) + : state(WHITESPACE) + , messages(0) + , untranslated(0) + , fuzzy(0) + , isFuzzy(false) + , isTranslated(false) { } void POExtractor::endMessage() { messages++; - if (isTranslated) fuzzy+=isFuzzy; - untranslated+=(!isTranslated); + if (isTranslated) fuzzy += isFuzzy; + untranslated += (!isTranslated); isFuzzy = false; isTranslated = false; @@ -79,25 +79,25 @@ state = ERROR; } return; - } else if (length > 1 && data[0] == '"' && data[length-1] == '"' - && (state == MSGCTXT || state == MSGID || state == MSGSTR - || state == MSGID_PLURAL)) { + } else if (length > 1 && data[0] == '"' && data[length - 1] == '"' + && (state == MSGCTXT || state == MSGID || state == MSGSTR + || state == MSGID_PLURAL)) { // continued text field isTranslated = state == MSGSTR && length > 2; } else if (state == MSGCTXT - && length > 7 && strncmp("msgid \"", data, 7) == 0) { + && length > 7 && strncmp("msgid \"", data, 7) == 0) { state = MSGID; } else if (state == MSGID - && length > 14 && strncmp("msgid_plural \"", data, 14) == 0) { + && length > 14 && strncmp("msgid_plural \"", data, 14) == 0) { state = MSGID_PLURAL; } else if ((state == MSGID || state == MSGID_PLURAL || state == MSGSTR) - && length > 8 && strncmp("msgstr", data, 6) == 0) { + && length > 8 && strncmp("msgstr", data, 6) == 0) { state = MSGSTR; - isTranslated = strncmp(data+length-3, " \"\"", 3) != 0; + isTranslated = strncmp(data + length - 3, " \"\"", 3) != 0; } else if (state == MSGSTR) { if (length == 0) { endMessage(); - } else if (data[0]=='#' || data[0]=='m') { //allow PO without empty line between entries + } else if (data[0] == '#' || data[0] == 'm') { //allow PO without empty line between entries endMessage(); state = COMMENT; handleLine(data, length); @@ -146,39 +146,38 @@ handleLine(line.c_str(), line.size()); lines++; - if (messages <= 1 && state == MSGSTR) - { + if (messages <= 1 && state == MSGSTR) { // handle special values in the first messsage // assumption is that value takes up only one line if (strncmp("\"POT-Creation-Date: ", line.c_str(), 20) == 0) { - m.sourceDate=QByteArray(line.c_str() + 20, line.size() - 21 - 2 ); + m.sourceDate = QByteArray(line.c_str() + 20, line.size() - 21 - 2); } else if (strncmp("\"PO-Revision-Date: ", line.c_str(), 19) == 0) { - m.translationDate=QByteArray(line.c_str() + 19, line.size() - 20 - 2); + m.translationDate = QByteArray(line.c_str() + 19, line.size() - 20 - 2); } else if (strncmp("\"Last-Translator: ", line.c_str(), 18) == 0) { - m.lastTranslator=QString::fromUtf8(QByteArray::fromRawData(line.c_str() + 18, line.size() - 19 - 2)); + m.lastTranslator = QString::fromUtf8(QByteArray::fromRawData(line.c_str() + 18, line.size() - 19 - 2)); } fuzzy = 0; } } handleLine("", 0); //for files with non-empty last line messages--;//cause header does not count -/* - result->add(Property::TranslationUnitsTotal, messages); - result->add(Property::TranslationUnitsWithTranslation, messages-untranslated); - result->add(Property::TranslationUnitsWithDraftTranslation, fuzzy); - result->add(Property::LineCount, lines); -*/ + /* + result->add(Property::TranslationUnitsTotal, messages); + result->add(Property::TranslationUnitsWithTranslation, messages-untranslated); + result->add(Property::TranslationUnitsWithDraftTranslation, fuzzy); + result->add(Property::LineCount, lines); + */ //TODO WordCount m.fuzzy = fuzzy; - m.translated = messages-untranslated-fuzzy; - m.untranslated=untranslated; + m.translated = messages - untranslated - fuzzy; + m.untranslated = untranslated; m.filePath = filePath; - Q_ASSERT(messages>=0 && fuzzy>=0 && untranslated>=0); + Q_ASSERT(messages >= 0 && fuzzy >= 0 && untranslated >= 0); //TODO - m.translated_approver=m.translated_reviewer=m.translated; - m.fuzzy_approver=m.fuzzy_reviewer=m.fuzzy; + m.translated_approver = m.translated_reviewer = m.translated; + m.fuzzy_approver = m.fuzzy_reviewer = m.fuzzy; } diff --git a/src/project/project.h b/src/project/project.h --- a/src/project/project.h +++ b/src/project/project.h @@ -33,9 +33,18 @@ class ProjectModel; class ProjectLocal; -namespace GlossaryNS{class Glossary;} -namespace GlossaryNS{class GlossaryWindow;} -namespace TM{class TMManagerWin;} +namespace GlossaryNS +{ +class Glossary; +} +namespace GlossaryNS +{ +class GlossaryWindow; +} +namespace TM +{ +class TMManagerWin; +} /** * Singleton object that represents project. @@ -57,45 +66,96 @@ explicit Project(); virtual ~Project(); - bool isLoaded()const{return !m_path.isEmpty();} + bool isLoaded()const + { + return !m_path.isEmpty(); + } ProjectModel* model(); //void setPath(const QString& p){m_path=p;} - QString path()const{return m_path;} - QString projectDir()const{return m_projectDir;} - QString poDir()const{return absolutePath(poBaseDir());} - QString potDir()const{return absolutePath(potBaseDir());} - QString branchDir()const{return absolutePath(ProjectBase::branchDir());} - QString glossaryPath()const{return absolutePath(glossaryTbx());} - QString qaPath()const{return absolutePath(mainQA());} - GlossaryNS::Glossary* glossary()const{return m_glossary;} - QString altTransDir()const{return absolutePath(altDir());} + QString path()const + { + return m_path; + } + QString projectDir()const + { + return m_projectDir; + } + QString poDir()const + { + return absolutePath(poBaseDir()); + } + QString potDir()const + { + return absolutePath(potBaseDir()); + } + QString branchDir()const + { + return absolutePath(ProjectBase::branchDir()); + } + QString glossaryPath()const + { + return absolutePath(glossaryTbx()); + } + QString qaPath()const + { + return absolutePath(mainQA()); + } + GlossaryNS::Glossary* glossary()const + { + return m_glossary; + } + QString altTransDir()const + { + return absolutePath(altDir()); + } bool queryCloseForAuxiliaryWindows(); void setDefaults(); // private slots: // void initLater(); public slots: - Q_SCRIPTABLE void load(const QString& newProjectPath, const QString& defaultTargetLangCode=QString(), const QString& defaultProjectId=QString()); + Q_SCRIPTABLE void load(const QString& newProjectPath, const QString& defaultTargetLangCode = QString(), const QString& defaultProjectId = QString()); Q_SCRIPTABLE void reinit(); Q_SCRIPTABLE void save(); - Q_SCRIPTABLE QString translationsRoot()const{return poDir();} - Q_SCRIPTABLE QString templatesRoot()const{return potDir();} - - - Q_SCRIPTABLE QString targetLangCode()const{return ProjectBase::langCode();} - Q_SCRIPTABLE QString sourceLangCode()const{return ProjectBase::sourceLangCode();} + Q_SCRIPTABLE QString translationsRoot()const + { + return poDir(); + } + Q_SCRIPTABLE QString templatesRoot()const + { + return potDir(); + } + + + Q_SCRIPTABLE QString targetLangCode()const + { + return ProjectBase::langCode(); + } + Q_SCRIPTABLE QString sourceLangCode()const + { + return ProjectBase::sourceLangCode(); + } Q_SCRIPTABLE void init(const QString& path, const QString& kind, const QString& id, const QString& sourceLang, const QString& targetLang); - Q_SCRIPTABLE QString kind()const{return ProjectBase::kind();} + Q_SCRIPTABLE QString kind()const + { + return ProjectBase::kind(); + } Q_SCRIPTABLE QString absolutePath(const QString&) const; - Q_SCRIPTABLE void setDesirablePath(const QString& path){m_desirablePath=path;} - Q_SCRIPTABLE QString desirablePath() const{return m_desirablePath;} + Q_SCRIPTABLE void setDesirablePath(const QString& path) + { + m_desirablePath = path; + } + Q_SCRIPTABLE QString desirablePath() const + { + return m_desirablePath; + } Q_SCRIPTABLE bool isTmSupported() const; @@ -110,19 +170,25 @@ void showTMManager(); GlossaryNS::GlossaryWindow* showGlossary(); - GlossaryNS::GlossaryWindow* defineNewTerm(QString en=QString(),QString target=QString()); + GlossaryNS::GlossaryWindow* defineNewTerm(QString en = QString(), QString target = QString()); void projectOdfCreate(); private: static Project* _instance; static void cleanupProject(); public: static Project* instance(); - static ProjectLocal* local(){return instance()->m_localConfig;} + static ProjectLocal* local() + { + return instance()->m_localConfig; + } const QMultiMap& sourceFilePaths(); - void resetSourceFilePaths(){m_sourceFilePaths.clear();} + void resetSourceFilePaths() + { + m_sourceFilePaths.clear(); + } friend class FillSourceFilePathsJob; signals: @@ -141,7 +207,7 @@ //cache QString m_projectDir; - }; +}; diff --git a/src/project/project.cpp b/src/project/project.cpp --- a/src/project/project.cpp +++ b/src/project/project.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -67,50 +67,49 @@ QString getMailingList() { QString lang = QLocale::system().name(); - if(lang.startsWith(QLatin1String("ca"))) + if (lang.startsWith(QLatin1String("ca"))) return QLatin1String("kde-i18n-ca@kde.org"); - if(lang.startsWith(QLatin1String("de"))) + if (lang.startsWith(QLatin1String("de"))) return QLatin1String("kde-i18n-de@kde.org"); - if(lang.startsWith(QLatin1String("hu"))) + if (lang.startsWith(QLatin1String("hu"))) return QLatin1String("kde-l10n-hu@kde.org"); - if(lang.startsWith(QLatin1String("tr"))) + if (lang.startsWith(QLatin1String("tr"))) return QLatin1String("kde-l10n-tr@kde.org"); - if(lang.startsWith(QLatin1String("it"))) + if (lang.startsWith(QLatin1String("it"))) return QLatin1String("kde-i18n-it@kde.org"); - if(lang.startsWith(QLatin1String("lt"))) + if (lang.startsWith(QLatin1String("lt"))) return QLatin1String("kde-i18n-lt@kde.org"); - if(lang.startsWith(QLatin1String("nb"))) + if (lang.startsWith(QLatin1String("nb"))) return QLatin1String("i18n-nb@lister.ping.uio.no"); - if(lang.startsWith(QLatin1String("nl"))) + if (lang.startsWith(QLatin1String("nl"))) return QLatin1String("kde-i18n-nl@kde.org"); - if(lang.startsWith(QLatin1String("nn"))) + if (lang.startsWith(QLatin1String("nn"))) return QLatin1String("i18n-nn@lister.ping.uio.no"); - if(lang.startsWith(QLatin1String("pt_BR"))) + if (lang.startsWith(QLatin1String("pt_BR"))) return QLatin1String("kde-i18n-pt_BR@kde.org"); - if(lang.startsWith(QLatin1String("ru"))) + if (lang.startsWith(QLatin1String("ru"))) return QLatin1String("kde-russian@lists.kde.ru"); - if(lang.startsWith(QLatin1String("se"))) + if (lang.startsWith(QLatin1String("se"))) return QLatin1String("i18n-sme@lister.ping.uio.no"); - if(lang.startsWith(QLatin1String("sl"))) + if (lang.startsWith(QLatin1String("sl"))) return QLatin1String("lugos-slo@lugos.si"); return QLatin1String("kde-i18n-doc@kde.org"); } -Project* Project::_instance=0; +Project* Project::_instance = 0; void Project::cleanupProject() { delete Project::_instance; Project::_instance = 0; } Project* Project::instance() { - if (_instance==0 ) - { - _instance=new Project(); + if (_instance == 0) { + _instance = new Project(); qAddPostRoutine(Project::cleanupProject); } return _instance; @@ -125,10 +124,10 @@ , m_tmManagerWindow(0) { setDefaults(); -/* - qRegisterMetaType("DocPosition"); - qDBusRegisterMetaType(); -*/ + /* + qRegisterMetaType("DocPosition"); + qDBusRegisterMetaType(); + */ //QTimer::singleShot(66,this,SLOT(initLater())); } /* @@ -154,14 +153,13 @@ void Project::load(const QString &newProjectPath, const QString& forcedTargetLangCode, const QString& forcedProjectId) { - QTime a;a.start(); + QTime a; a.start(); TM::threadPool()->clear(); - qCDebug(LOKALIZE_LOG)<<"loading"<setAutoDelete(true); TM::threadPool()->start(closeDBJob, CLOSEDB); } @@ -173,13 +171,13 @@ ProjectBase::load(); #else #endif - m_path=newProjectPath; + m_path = newProjectPath; m_desirablePath.clear(); //cache: - m_projectDir=QFileInfo(m_path).absolutePath(); + m_projectDir = QFileInfo(m_path).absolutePath(); #ifndef NOKDE - m_localConfig->setSharedConfig(KSharedConfig::openConfig(projectID()+QStringLiteral(".local"), KConfig::NoGlobals,QStandardPaths::DataLocation)); + m_localConfig->setSharedConfig(KSharedConfig::openConfig(projectID() + QStringLiteral(".local"), KConfig::NoGlobals, QStandardPaths::DataLocation)); m_localConfig->load(); #endif @@ -208,12 +206,11 @@ if (!isTmSupported()) - qCWarning(LOKALIZE_LOG)<<"no sqlite module available"; + qCWarning(LOKALIZE_LOG) << "no sqlite module available"; //NOTE do we need to explicitly call it when project id changes? TM::DBFilesModel::instance()->openDB(projectID(), TM::Undefined, true); - if (QaModel::isInstantiated()) - { + if (QaModel::isInstantiated()) { QaModel::instance()->saveRules(); QaModel::instance()->loadRules(qaPath()); } @@ -226,7 +223,7 @@ void Project::reinit() { - TM::CloseDBJob* closeDBJob=new TM::CloseDBJob(projectID()); + TM::CloseDBJob* closeDBJob = new TM::CloseDBJob(projectID()); closeDBJob->setAutoDelete(true); TM::threadPool()->start(closeDBJob, CLOSEDB); @@ -247,12 +244,12 @@ void Project::populateDirModel() { #ifndef NOKDE - if (Q_UNLIKELY( m_path.isEmpty() || !QFileInfo::exists(poDir()) )) + if (Q_UNLIKELY(m_path.isEmpty() || !QFileInfo::exists(poDir()))) return; QUrl potUrl; if (QFileInfo::exists(potDir())) - potUrl=QUrl::fromLocalFile(potDir()); + potUrl = QUrl::fromLocalFile(potDir()); model()->setUrl(QUrl::fromLocalFile(poDir()), potUrl); #endif } @@ -273,40 +270,38 @@ return 0; if (!m_glossaryWindow) - m_glossaryWindow=new GlossaryNS::GlossaryWindow(SettingsController::instance()->mainWindowPtr()); + m_glossaryWindow = new GlossaryNS::GlossaryWindow(SettingsController::instance()->mainWindowPtr()); m_glossaryWindow->show(); m_glossaryWindow->activateWindow(); - if (!en.isEmpty()||!target.isEmpty()) - m_glossaryWindow->newTermEntry(en,target); - + if (!en.isEmpty() || !target.isEmpty()) + m_glossaryWindow->newTermEntry(en, target); + return m_glossaryWindow; } bool Project::queryCloseForAuxiliaryWindows() { if (m_glossaryWindow && m_glossaryWindow->isVisible()) return m_glossaryWindow->queryClose(); - + return true; } bool Project::isTmSupported() const { - QStringList drivers=QSqlDatabase::drivers(); + QStringList drivers = QSqlDatabase::drivers(); return drivers.contains(QLatin1String("QSQLITE")); } void Project::showTMManager() { - if (!m_tmManagerWindow) - { - if (!isTmSupported()) - { + if (!m_tmManagerWindow) { + if (!isTmSupported()) { KMessageBox::information(0, i18n("TM facility requires SQLite Qt module."), i18n("No SQLite module available")); return; } - m_tmManagerWindow=new TM::TMManagerWin(SettingsController::instance()->mainWindowPtr()); + m_tmManagerWindow = new TM::TMManagerWin(SettingsController::instance()->mainWindowPtr()); } m_tmManagerWindow->show(); m_tmManagerWindow->activateWindow(); @@ -325,7 +320,7 @@ { #ifndef NOKDE if (Q_UNLIKELY(!m_model)) - m_model=new ProjectModel(this); + m_model = new ProjectModel(this); return m_model; #else @@ -343,41 +338,42 @@ const QString& sourceLang, const QString& targetLang) { setDefaults(); - bool stop=false; - while(true) - { - setKind(kind);setSourceLangCode(sourceLang);setLangCode(targetLang);setProjectID(id); + bool stop = false; + while (true) { + setKind(kind); setSourceLangCode(sourceLang); setLangCode(targetLang); setProjectID(id); if (stop) break; - else {load(path);stop=true;} + else { + load(path); + stop = true; + } } save(); } static void fillFilePathsRecursive(const QDir& dir, QMultiMap& sourceFilePaths) { - QStringList subDirs(dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot|QDir::Readable)); - int i=subDirs.size(); - while(--i>=0) - fillFilePathsRecursive(QDir(dir.filePath(subDirs.at(i))),sourceFilePaths); + QStringList subDirs(dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Readable)); + int i = subDirs.size(); + while (--i >= 0) + fillFilePathsRecursive(QDir(dir.filePath(subDirs.at(i))), sourceFilePaths); static QStringList filters = QStringList(QStringLiteral("*.cpp")) - <=0) - { + << QStringLiteral("*.c") + << QStringLiteral("*.cc") + << QStringLiteral("*.mm") + << QStringLiteral("*.ui") + << QStringLiteral("*rc"); + QStringList files(dir.entryList(filters, QDir::Files | QDir::NoDotAndDotDot | QDir::Readable)); + i = files.size(); + + QByteArray absDirPath = dir.absolutePath().toUtf8(); absDirPath.squeeze(); + while (--i >= 0) { //qCDebug(LOKALIZE_LOG)<sourceFilePathsAreReady();} + void finish() + { + emitResult(); + emit Project::instance()->sourceFilePathsAreReady(); + } protected: bool doKill(); @@ -415,7 +415,7 @@ class FillSourceFilePathsJob: public QRunnable { public: - explicit FillSourceFilePathsJob(const QDir& dir, SourceFilesSearchJob* j):startingDir(dir),kj(j){} + explicit FillSourceFilePathsJob(const QDir& dir, SourceFilesSearchJob* j): startingDir(dir), kj(j) {} protected: void run() @@ -435,18 +435,16 @@ { QThreadPool::globalInstance()->start(new FillSourceFilePathsJob(QDir(m_folderName), this)); emit description(this, - i18n("Scanning folders with source files"), - qMakePair(i18n("Editor"), m_folderName)); + i18n("Scanning folders with source files"), + qMakePair(i18n("Editor"), m_folderName)); } #endif const QMultiMap& Project::sourceFilePaths() { - if (m_sourceFilePaths.isEmpty()) - { + if (m_sourceFilePaths.isEmpty()) { QDir dir(local()->sourceDir()); - if (dir.exists()) - { + if (dir.exists()) { #ifndef NOKDE SourceFilesSearchJob* metaJob = new SourceFilesSearchJob(local()->sourceDir()); KIO::getJobTracker()->registerJob(metaJob); @@ -473,35 +471,34 @@ #include "languagelistmodel.h" void Project::projectOdfCreate() { - QString odf2xliff=QStringLiteral("odf2xliff"); - if (QProcess::execute(odf2xliff, QStringList(QLatin1String("--version")))==-2) - { + QString odf2xliff = QStringLiteral("odf2xliff"); + if (QProcess::execute(odf2xliff, QStringList(QLatin1String("--version"))) == -2) { KMessageBox::error(SettingsController::instance()->mainWindowPtr(), i18n("Install translate-toolkit package and retry")); return; } - QString odfPath=QFileDialog::getOpenFileName(SettingsController::instance()->mainWindowPtr(), QString(), QDir::homePath()/*_catalog->url().directory()*/, - i18n("OpenDocument files (*.odt *.ods)")/*"text/x-lokalize-project"*/); + QString odfPath = QFileDialog::getOpenFileName(SettingsController::instance()->mainWindowPtr(), QString(), QDir::homePath()/*_catalog->url().directory()*/, + i18n("OpenDocument files (*.odt *.ods)")/*"text/x-lokalize-project"*/); if (odfPath.isEmpty()) return; - QString targetLangCode=getTargetLangCode(QString(), true); + QString targetLangCode = getTargetLangCode(QString(), true); QFileInfo fi(odfPath); - QString trFolderName=i18nc("project folder name. %2 is targetLangCode", "%1 %2 Translation", fi.baseName(), targetLangCode); + QString trFolderName = i18nc("project folder name. %2 is targetLangCode", "%1 %2 Translation", fi.baseName(), targetLangCode); fi.absoluteDir().mkdir(trFolderName); QStringList args(odfPath); args.append(fi.absoluteDir().absoluteFilePath(trFolderName) % '/' % fi.baseName() % QLatin1String(".xlf")); - qCDebug(LOKALIZE_LOG)<load(fi.absoluteDir().absoluteFilePath(trFolderName)+QLatin1String("/index.lokalize"), targetLangCode, fi.baseName()%'-'%targetLangCode); + Project::instance()->load(fi.absoluteDir().absoluteFilePath(trFolderName) + QLatin1String("/index.lokalize"), targetLangCode, fi.baseName() % '-' % targetLangCode); emit fileOpenRequested(args.at(1)); } diff --git a/src/project/projectmodel.h b/src/project/projectmodel.h --- a/src/project/projectmodel.h +++ b/src/project/projectmodel.h @@ -10,7 +10,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -39,8 +39,7 @@ class QThreadPool; class UpdateStatsJob; -struct FileMetaData -{ +struct FileMetaData { int translated; int translated_reviewer; int translated_approver; @@ -56,8 +55,8 @@ QString filePath; FileMetaData() - : translated(0), translated_reviewer(0), translated_approver(0), untranslated(0) - , fuzzy(0), fuzzy_reviewer(0), fuzzy_approver(0) + : translated(0), translated_reviewer(0), translated_approver(0), untranslated(0) + , fuzzy(0), fuzzy_reviewer(0), fuzzy_approver(0) {} }; @@ -83,33 +82,31 @@ ~ProjectNode(); void calculateDirStats(); void setFileStats(const FileMetaData& info); - + int translatedAsPerRole() const { - switch (Project::local()->role()) - { - case ProjectLocal::Translator: - case ProjectLocal::Undefined: - return translated; - case ProjectLocal::Reviewer: - return translated_reviewer; - case ProjectLocal::Approver: - return translated_approver; + switch (Project::local()->role()) { + case ProjectLocal::Translator: + case ProjectLocal::Undefined: + return translated; + case ProjectLocal::Reviewer: + return translated_reviewer; + case ProjectLocal::Approver: + return translated_approver; } return -1; } - + int fuzzyAsPerRole() const { - switch (Project::local()->role()) - { - case ProjectLocal::Translator: - case ProjectLocal::Undefined: - return fuzzy; - case ProjectLocal::Reviewer: - return fuzzy_reviewer; - case ProjectLocal::Approver: - return fuzzy_approver; + switch (Project::local()->role()) { + case ProjectLocal::Translator: + case ProjectLocal::Undefined: + return fuzzy; + case ProjectLocal::Reviewer: + return fuzzy_reviewer; + case ProjectLocal::Approver: + return fuzzy_approver; } return -1; } @@ -138,8 +135,7 @@ public: - enum ProjectModelColumns - { + enum ProjectModelColumns { FileName, Graph, TotalCount, @@ -186,8 +182,14 @@ bool canFetchMore(const QModelIndex& parent) const; void fetchMore(const QModelIndex& parent); - QThreadPool* threadPool(){return m_threadPool;} - void setCompleteScan(bool enable){m_completeScan=enable;} + QThreadPool* threadPool() + { + return m_threadPool; + } + void setCompleteScan(bool enable) + { + m_completeScan = enable; + } signals: void totalsChanged(int fuzzy, int translated, int untranslated, bool done); @@ -267,9 +269,12 @@ { Q_OBJECT public: - explicit UpdateStatsJob(QList files, QObject* owner=0); + explicit UpdateStatsJob(QList files, QObject* owner = 0); ~UpdateStatsJob(); - int priority()const{return 35;} //SEE jobs.h + int priority()const + { + return 35; //SEE jobs.h + } void setStatus(int status); diff --git a/src/project/projectmodel.cpp b/src/project/projectmodel.cpp --- a/src/project/projectmodel.cpp +++ b/src/project/projectmodel.cpp @@ -10,7 +10,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -45,7 +45,7 @@ #include -static int nodeCounter=0; +static int nodeCounter = 0; //TODO: figure out how to handle file and folder renames... //TODO: fix behavior on folder removing, adding. @@ -105,7 +105,7 @@ m_activeJob->setStatus(-2); m_activeJob = NULL; - + for (int pos = 0; pos < m_rootNode.rows.count(); pos ++) deleteSubtree(m_rootNode.rows.at(pos)); } @@ -124,8 +124,7 @@ m_activeJob->setStatus(-1); m_activeJob = NULL; - if (m_rootNode.rows.count()) - { + if (m_rootNode.rows.count()) { beginRemoveRows(QModelIndex(), 0, m_rootNode.rows.count()); for (int pos = 0; pos < m_rootNode.rows.count(); pos ++) @@ -161,13 +160,10 @@ QModelIndex poIndex = poIndexForOuter(index); QModelIndex potIndex = potIndexForOuter(index); - if (poIndex.isValid()) - { + if (poIndex.isValid()) { KFileItem item = m_poModel.itemForIndex(poIndex); return item.url(); - } - else if (potIndex.isValid()) - { + } else if (potIndex.isValid()) { //copy over the file QUrl potFile = m_potModel.itemForIndex(potIndex).url(); QUrl poFile = potToPo(potFile); @@ -178,9 +174,7 @@ // KIO::NetAccess::file_copy(potFile, poFile); return poFile; - } - else - { + } else { Q_ASSERT(false); return QUrl(); } @@ -208,15 +202,13 @@ QModelIndex topLeft = indexForPoIndex(po_topLeft); QModelIndex bottomRight = indexForPoIndex(po_bottomRight); - if (topLeft.row()==bottomRight.row() && itemForIndex(topLeft).isFile()) - { + if (topLeft.row() == bottomRight.row() && itemForIndex(topLeft).isFile()) { //this code works fine only for lonely files //and fails for more complex changes //see bug 342959 emit dataChanged(topLeft, bottomRight); enqueueNodeForMetadataUpdate(nodeForIndex(topLeft.parent())); - } - else + } else m_delayedReloadTimer->start(1000); } @@ -234,7 +226,7 @@ int count = node->rows.count(); QModelIndex topLeft = index(0, pot_topLeft.column(), parent); - QModelIndex bottomRight = index(count-1, pot_bottomRight.column(), parent); + QModelIndex bottomRight = index(count - 1, pot_bottomRight.column(), parent); emit dataChanged(topLeft, bottomRight); @@ -256,8 +248,7 @@ //insert po rows beginInsertRows(parent, first, last); - for (int pos = first; pos <= last; pos ++) - { + for (int pos = first; pos <= last; pos ++) { ProjectNode * childNode = new ProjectNode(node, pos, pos, -1); node->rows.insert(pos, childNode); } @@ -271,19 +262,16 @@ endInsertRows(); //remove unneeded pot rows, update PO rows - if (pot_parent.isValid() || !parent.isValid()) - { + if (pot_parent.isValid() || !parent.isValid()) { QVector pot2PoMapping; generatePOTMapping(pot2PoMapping, po_parent, pot_parent); - for (int pos = node->poCount; pos < node->rows.count(); pos ++) - { + for (int pos = node->poCount; pos < node->rows.count(); pos ++) { ProjectNode* potNode = node->rows.at(pos); int potIndex = potNode->potRowNumber; int poIndex = pot2PoMapping[potIndex]; - if (poIndex != -1) - { + if (poIndex != -1) { //found pot node, that now has a PO index. //remove the pot node and change the corresponding PO node beginRemoveRows(parent, pos, pos); @@ -313,65 +301,55 @@ int insertedCount = end + 1 - start; QVector newPotNodes; - if (po_parent.isValid() || !parent.isValid()) - { + if (po_parent.isValid() || !parent.isValid()) { //this node containts mixed items - add and merge the stuff QVector pot2PoMapping; generatePOTMapping(pot2PoMapping, po_parent, pot_parent); //reassign affected PO row POT indices - for (int pos = 0; pos < node->poCount;pos ++) - { - ProjectNode* n=node->rows[pos]; + for (int pos = 0; pos < node->poCount; pos ++) { + ProjectNode* n = node->rows[pos]; if (n->potRowNumber >= start) n->potRowNumber += insertedCount; } //assign new POT indices - for (int potIndex = start; potIndex <= end; potIndex ++) - { + for (int potIndex = start; potIndex <= end; potIndex ++) { int poIndex = pot2PoMapping[potIndex]; - if (poIndex != -1) - { + if (poIndex != -1) { //found pot node, that has a PO index. //change the corresponding PO node node->rows[poIndex]->potRowNumber = potIndex; //This change does not need notification //dataChanged(index(poIndex, 0, parent), index(poIndex, ProjectModelColumnCount, parent)); - } - else + } else newPotNodes.append(potIndex); } - } - else - { + } else { for (int pos = start; pos < end; pos ++) newPotNodes.append(pos); } //insert standalone POT rows, preserving POT order int newNodesCount = newPotNodes.count(); - if (newNodesCount) - { + if (newNodesCount) { int insertionPoint = node->poCount; while ((insertionPoint < node->rows.count()) && (node->rows[insertionPoint]->potRowNumber < start)) insertionPoint++; beginInsertRows(parent, insertionPoint, insertionPoint + newNodesCount - 1); - for (int pos = 0; pos < newNodesCount; pos ++) - { + for (int pos = 0; pos < newNodesCount; pos ++) { int potIndex = newPotNodes.at(pos); ProjectNode * childNode = new ProjectNode(node, insertionPoint, -1, potIndex); node->rows.insert(insertionPoint, childNode); insertionPoint++; } //renumber remaining POT rows - for (int pos = insertionPoint; pos < node->rows.count(); pos ++) - { + for (int pos = insertionPoint; pos < node->rows.count(); pos ++) { node->rows[pos]->rowNumber = pos; node->rows[pos]->potRowNumber += insertedCount; } @@ -391,9 +369,8 @@ ProjectNode* node = nodeForIndex(parent); int removedCount = end + 1 - start; - if ((!parent.isValid()) && (node->rows.count() == 0)) - { - qCDebug(LOKALIZE_LOG)<<"po_rowsRemoved fail"; + if ((!parent.isValid()) && (node->rows.count() == 0)) { + qCDebug(LOKALIZE_LOG) << "po_rowsRemoved fail"; //events after removing entire contents return; } @@ -404,18 +381,16 @@ beginRemoveRows(parent, start, end); //renumber all rows after removed. - for (int pos = end + 1; pos < node->rows.count(); pos ++) - { + for (int pos = end + 1; pos < node->rows.count(); pos ++) { ProjectNode* childNode = node->rows.at(pos); childNode->rowNumber -= removedCount; if (childNode->poRowNumber > end) node->rows[pos]->poRowNumber -= removedCount; } //remove - for (int pos = end; pos >= start; pos --) - { + for (int pos = end; pos >= start; pos --) { int potIndex = node->rows.at(pos)->potRowNumber; deleteSubtree(node->rows.at(pos)); node->rows.remove(pos); @@ -434,11 +409,9 @@ int insertionPoint = node->poCount; - for (int pos = 0; pos < potRowsToInsert.count(); pos ++) - { + for (int pos = 0; pos < potRowsToInsert.count(); pos ++) { int potIndex = potRowsToInsert.at(pos); - while (insertionPoint < node->rows.count() && node->rows[insertionPoint]->potRowNumber < potIndex) - { + while (insertionPoint < node->rows.count() && node->rows[insertionPoint]->potRowNumber < potIndex) { node->rows[insertionPoint]->rowNumber = insertionPoint; insertionPoint ++; } @@ -452,8 +425,7 @@ } //renumber remaining rows - while (insertionPoint < node->rows.count()) - { + while (insertionPoint < node->rows.count()) { node->rows[insertionPoint]->rowNumber = insertionPoint; insertionPoint++; } @@ -469,8 +441,7 @@ ProjectNode * node = nodeForIndex(parent); int removedCount = end + 1 - start; - if ((!parent.isValid()) && (node->rows.count() == 0)) - { + if ((!parent.isValid()) && (node->rows.count() == 0)) { //events after removing entire contents return; } @@ -485,22 +456,19 @@ while (lastPOTToRemove >= firstPOTToRemove && node->rows[lastPOTToRemove]->potRowNumber > end) lastPOTToRemove --; - if (firstPOTToRemove <= lastPOTToRemove) - { + if (firstPOTToRemove <= lastPOTToRemove) { beginRemoveRows(parent, firstPOTToRemove, lastPOTToRemove); - for (int pos = lastPOTToRemove; pos >= firstPOTToRemove; pos --) - { + for (int pos = lastPOTToRemove; pos >= firstPOTToRemove; pos --) { ProjectNode* childNode = node->rows.at(pos); Q_ASSERT(childNode->potRowNumber >= start); Q_ASSERT(childNode->potRowNumber <= end); deleteSubtree(childNode); node->rows.remove(pos); } //renumber remaining rows - for (int pos = firstPOTToRemove; pos < node->rows.count(); pos ++) - { + for (int pos = firstPOTToRemove; pos < node->rows.count(); pos ++) { node->rows[pos]->rowNumber = pos; node->rows[pos]->potRowNumber -= removedCount; } @@ -510,23 +478,18 @@ //now remove POT indices form PO rows - if (po_parent.isValid() || !parent.isValid()) - { - for (int poIndex = 0; poIndex < node->poCount; poIndex ++) - { + if (po_parent.isValid() || !parent.isValid()) { + for (int poIndex = 0; poIndex < node->poCount; poIndex ++) { ProjectNode * childNode = node->rows[poIndex]; int potIndex = childNode->potRowNumber; - if (potIndex >= start && potIndex <= end) - { + if (potIndex >= start && potIndex <= end) { //found PO node, that has a POT index in range. //change the corresponding PO node node->rows[poIndex]->potRowNumber = -1; //this change does not affect the model //dataChanged(index(poIndex, 0, parent), index(poIndex, ProjectModelColumnCount, parent)); - } - else if (childNode->potRowNumber > end) - { + } else if (childNode->potRowNumber > end) { //reassign POT indices childNode->potRowNumber -= removedCount; } @@ -545,60 +508,55 @@ QVariant ProjectModel::headerData(int section, Qt::Orientation, int role) const { - switch(role) - { - case Qt::TextAlignmentRole: - { - switch (section) - { - // Align numeric columns to the right and other columns to the left - // Qt::AlignAbsolute is needed for RTL languages, ref. https://phabricator.kde.org/D13098 - case TotalCount: return QVariant(Qt::AlignRight | Qt::AlignAbsolute); - case TranslatedCount: return QVariant(Qt::AlignRight | Qt::AlignAbsolute); - case FuzzyCount: return QVariant(Qt::AlignRight | Qt::AlignAbsolute); - case UntranslatedCount: return QVariant(Qt::AlignRight | Qt::AlignAbsolute); - case IncompleteCount: return QVariant(Qt::AlignRight | Qt::AlignAbsolute); - default: return QVariant(Qt::AlignLeft); - } + switch (role) { + case Qt::TextAlignmentRole: { + switch (section) { + // Align numeric columns to the right and other columns to the left + // Qt::AlignAbsolute is needed for RTL languages, ref. https://phabricator.kde.org/D13098 + case TotalCount: return QVariant(Qt::AlignRight | Qt::AlignAbsolute); + case TranslatedCount: return QVariant(Qt::AlignRight | Qt::AlignAbsolute); + case FuzzyCount: return QVariant(Qt::AlignRight | Qt::AlignAbsolute); + case UntranslatedCount: return QVariant(Qt::AlignRight | Qt::AlignAbsolute); + case IncompleteCount: return QVariant(Qt::AlignRight | Qt::AlignAbsolute); + default: return QVariant(Qt::AlignLeft); } - case Qt::DisplayRole: - { - switch (section) - { - case FileName: return i18nc("@title:column File name","Name"); - case Graph: return i18nc("@title:column Graphical representation of Translated/Fuzzy/Untranslated counts","Graph"); - case TotalCount: return i18nc("@title:column Number of entries","Total"); - case TranslatedCount: return i18nc("@title:column Number of entries","Translated"); - case FuzzyCount: return i18nc("@title:column Number of entries","Not ready"); - case UntranslatedCount: return i18nc("@title:column Number of entries","Untranslated"); - case IncompleteCount: return i18nc("@title:column Number of fuzzy or untranslated entries","Incomplete"); - case TranslationDate: return i18nc("@title:column","Last Translation"); - case SourceDate: return i18nc("@title:column","Template Revision"); - case LastTranslator: return i18nc("@title:column","Last Translator"); - default: return QVariant(); - } + } + case Qt::DisplayRole: { + switch (section) { + case FileName: return i18nc("@title:column File name", "Name"); + case Graph: return i18nc("@title:column Graphical representation of Translated/Fuzzy/Untranslated counts", "Graph"); + case TotalCount: return i18nc("@title:column Number of entries", "Total"); + case TranslatedCount: return i18nc("@title:column Number of entries", "Translated"); + case FuzzyCount: return i18nc("@title:column Number of entries", "Not ready"); + case UntranslatedCount: return i18nc("@title:column Number of entries", "Untranslated"); + case IncompleteCount: return i18nc("@title:column Number of fuzzy or untranslated entries", "Incomplete"); + case TranslationDate: return i18nc("@title:column", "Last Translation"); + case SourceDate: return i18nc("@title:column", "Template Revision"); + case LastTranslator: return i18nc("@title:column", "Last Translator"); + default: return QVariant(); } - default: return QVariant(); + } + default: return QVariant(); } } -Qt::ItemFlags ProjectModel::flags( const QModelIndex & index ) const +Qt::ItemFlags ProjectModel::flags(const QModelIndex & index) const { if (index.column() == FileName) - return Qt::ItemIsSelectable|Qt::ItemIsEnabled; + return Qt::ItemIsSelectable | Qt::ItemIsEnabled; else return Qt::ItemIsSelectable; } -int ProjectModel::rowCount ( const QModelIndex & parent /*= QModelIndex()*/ ) const +int ProjectModel::rowCount(const QModelIndex & parent /*= QModelIndex()*/) const { return nodeForIndex(parent)->rows.size(); } -bool ProjectModel::hasChildren ( const QModelIndex & parent /*= QModelIndex()*/ ) const +bool ProjectModel::hasChildren(const QModelIndex & parent /*= QModelIndex()*/) const { if (!parent.isValid()) return true; @@ -610,7 +568,7 @@ (potIndex.isValid() && m_potModel.hasChildren(potIndex))); } -bool ProjectModel::canFetchMore ( const QModelIndex & parent ) const +bool ProjectModel::canFetchMore(const QModelIndex & parent) const { if (!parent.isValid()) return m_poModel.canFetchMore(QModelIndex()) || m_potModel.canFetchMore(QModelIndex()); @@ -622,18 +580,15 @@ (potIndex.isValid() && m_potModel.canFetchMore(potIndex))); } -void ProjectModel::fetchMore ( const QModelIndex & parent ) +void ProjectModel::fetchMore(const QModelIndex & parent) { - if (!parent.isValid()) - { + if (!parent.isValid()) { if (m_poModel.canFetchMore(QModelIndex())) m_poModel.fetchMore(QModelIndex()); if (m_potModel.canFetchMore(QModelIndex())) m_potModel.fetchMore(QModelIndex()); - } - else - { + } else { QModelIndex poIndex = poIndexForOuter(parent); QModelIndex potIndex = potIndexForOuter(parent); @@ -659,77 +614,73 @@ if (!index.isValid()) return QVariant(); - const ProjectModelColumns& column=(ProjectModelColumns)index.column(); + const ProjectModelColumns& column = (ProjectModelColumns)index.column(); ProjectNode* node = nodeForIndex(index); QModelIndex internalIndex = poOrPotIndexForOuter(index); if (!internalIndex.isValid()) return QVariant(); - KFileItem item=itemForIndex(index); + KFileItem item = itemForIndex(index); bool isDir = item.isDir(); int translated = node->translatedAsPerRole(); int fuzzy = node->fuzzyAsPerRole(); int untranslated = node->untranslated; bool hasStats = translated != -1; - switch(role) - { + switch (role) { case Qt::TextAlignmentRole: return ProjectModel::headerData(column, Qt::Horizontal, role); // Use same alignment as header case Qt::DisplayRole: - switch (column) - { - case FileName: return item.text(); - case Graph: return hasStats?QRect(translated, untranslated, fuzzy, 0):QVariant(); - case TotalCount: return hasStats?(translated + untranslated + fuzzy):QVariant(); - case TranslatedCount:return hasStats?translated:QVariant(); - case FuzzyCount: return hasStats?fuzzy:QVariant(); - case UntranslatedCount:return hasStats?untranslated:QVariant(); - case IncompleteCount:return hasStats?(untranslated + fuzzy):QVariant(); - case SourceDate: return node->sourceDate; - case TranslationDate:return node->translationDate; - case LastTranslator:return node->lastTranslator; - default: return QVariant(); + switch (column) { + case FileName: return item.text(); + case Graph: return hasStats ? QRect(translated, untranslated, fuzzy, 0) : QVariant(); + case TotalCount: return hasStats ? (translated + untranslated + fuzzy) : QVariant(); + case TranslatedCount: return hasStats ? translated : QVariant(); + case FuzzyCount: return hasStats ? fuzzy : QVariant(); + case UntranslatedCount: return hasStats ? untranslated : QVariant(); + case IncompleteCount: return hasStats ? (untranslated + fuzzy) : QVariant(); + case SourceDate: return node->sourceDate; + case TranslationDate: return node->translationDate; + case LastTranslator: return node->lastTranslator; + default: return QVariant(); } case Qt::ToolTipRole: - switch (column) - { - case FileName: return item.text(); - default: return QVariant(); + switch (column) { + case FileName: return item.text(); + default: return QVariant(); } case KDirModel::FileItemRole: return QVariant::fromValue(item); case Qt::DecorationRole: - switch (column) - { - case FileName: - if (isDir) - return m_dirIcon; - if (hasStats && fuzzy == 0 && untranslated == 0) - return m_poComplIcon; - else if (node->poRowNumber != -1) - return m_poIcon; - else if (node->potRowNumber != -1) - return m_potIcon; - default: - return QVariant(); + switch (column) { + case FileName: + if (isDir) + return m_dirIcon; + if (hasStats && fuzzy == 0 && untranslated == 0) + return m_poComplIcon; + else if (node->poRowNumber != -1) + return m_poIcon; + else if (node->potRowNumber != -1) + return m_potIcon; + default: + return QVariant(); } case FuzzyUntrCountAllRole: - return hasStats?(fuzzy + untranslated):0; + return hasStats ? (fuzzy + untranslated) : 0; case FuzzyUntrCountRole: - return item.isFile()?(fuzzy + untranslated):0; + return item.isFile() ? (fuzzy + untranslated) : 0; case FuzzyCountRole: - return item.isFile()?fuzzy:0; + return item.isFile() ? fuzzy : 0; case UntransCountRole: - return item.isFile()?untranslated:0; + return item.isFile() ? untranslated : 0; case TemplateOnlyRole: - return item.isFile()?(node->poRowNumber == -1):0; + return item.isFile() ? (node->poRowNumber == -1) : 0; case TransOnlyRole: - return item.isFile()?(node->potRowNumber == -1):0; + return item.isFile() ? (node->potRowNumber == -1) : 0; case TotalRole: - return hasStats?(fuzzy + untranslated + translated):0; + return hasStats ? (fuzzy + untranslated + translated) : 0; default: return QVariant(); } @@ -740,54 +691,48 @@ { ProjectNode* parentNode = nodeForIndex(parent); //qCWarning(LOKALIZE_LOG)<<(sizeof(ProjectNode))<=parentNode->rows.size()) - { - qCWarning(LOKALIZE_LOG)<<"Issues with indexes"<rows.size()<= parentNode->rows.size()) { + qCWarning(LOKALIZE_LOG) << "Issues with indexes" << row << parentNode->rows.size() << itemForIndex(parent).url(); return QModelIndex(); } return createIndex(row, column, parentNode->rows.at(row)); } KFileItem ProjectModel::itemForIndex(const QModelIndex& index) const { - if (!index.isValid()) - { + if (!index.isValid()) { //file item for root node. return m_poModel.itemForIndex(index); } QModelIndex poIndex = poIndexForOuter(index); if (poIndex.isValid()) return m_poModel.itemForIndex(poIndex); - else - { + else { QModelIndex potIndex = potIndexForOuter(index); if (potIndex.isValid()) return m_potModel.itemForIndex(potIndex); } - qCInfo(LOKALIZE_LOG)<<"returning empty KFileItem()"<(index.internalPointer())->untranslated<(index.internalPointer())->sourceDate; + qCInfo(LOKALIZE_LOG) << "returning empty KFileItem()" << index.row() << index.column(); + qCInfo(LOKALIZE_LOG) << "returning empty KFileItem()" << index.parent().isValid(); + qCInfo(LOKALIZE_LOG) << "returning empty KFileItem()" << index.parent().internalPointer(); + qCInfo(LOKALIZE_LOG) << "returning empty KFileItem()" << index.parent().data().toString(); + qCInfo(LOKALIZE_LOG) << "returning empty KFileItem()" << index.internalPointer(); + qCInfo(LOKALIZE_LOG) << "returning empty KFileItem()" << static_cast(index.internalPointer())->untranslated << static_cast(index.internalPointer())->sourceDate; return KFileItem(); } ProjectModel::ProjectNode* ProjectModel::nodeForIndex(const QModelIndex& index) const { - if (index.isValid()) - { + if (index.isValid()) { ProjectNode * node = static_cast(index.internalPointer()); Q_ASSERT(node != NULL); return node; - } - else - { + } else { ProjectNode * node = const_cast(&m_rootNode); Q_ASSERT(node != NULL); return node; @@ -807,13 +752,10 @@ QModelIndex ProjectModel::indexForUrl(const QUrl& url) { - if (m_poUrl.isParentOf(url)) - { + if (m_poUrl.isParentOf(url)) { QModelIndex poIndex = m_poModel.indexForUrl(url); return indexForPoIndex(poIndex); - } - else if (m_potUrl.isParentOf(url)) - { + } else if (m_potUrl.isParentOf(url)) { QModelIndex potIndex = m_potModel.indexForUrl(url); return indexForPotIndex(potIndex); } @@ -848,19 +790,18 @@ QModelIndex parent = outerIndex.parent(); QModelIndex internalParent; - if (parent.isValid()) - { + if (parent.isValid()) { internalParent = indexForOuter(parent, type); if (!internalParent.isValid()) return QModelIndex(); } ProjectNode* node = nodeForIndex(outerIndex); - short rowNumber=(type==PoIndex?node->poRowNumber:node->potRowNumber); + short rowNumber = (type == PoIndex ? node->poRowNumber : node->potRowNumber); if (rowNumber == -1) return QModelIndex(); - return (type==PoIndex?m_poModel:m_potModel).index(rowNumber, outerIndex.column(), internalParent); + return (type == PoIndex ? m_poModel : m_potModel).index(rowNumber, outerIndex.column(), internalParent); } QModelIndex ProjectModel::poIndexForOuter(const QModelIndex& outerIndex) const @@ -888,7 +829,7 @@ QModelIndex potIndex = potIndexForOuter(outerIndex); if (!potIndex.isValid()) - qCWarning(LOKALIZE_LOG)<<"error mapping index to PO or POT"; + qCWarning(LOKALIZE_LOG) << "error mapping index to PO or POT"; return potIndex; } @@ -915,13 +856,13 @@ int potRow = potIndex.row(); int row = 0; - while(rowrows.count() && node->rows.at(row)->potRowNumber!=potRow) + while (row < node->rows.count() && node->rows.at(row)->potRowNumber != potRow) row++; if (row != node->rows.count()) return index(row, potIndex.column(), outerParent); - qCWarning(LOKALIZE_LOG)<<"error mapping index from POT to outer, searched for potRow:"< poOccupiedUrls; - for (int poPos = 0; poPos < poRows; poPos ++) - { + for (int poPos = 0; poPos < poRows; poPos ++) { KFileItem file = m_poModel.itemForIndex(m_poModel.index(poPos, 0, poParent)); QUrl potUrl = poToPot(file.url()); poOccupiedUrls.append(potUrl); } - for (int potPos = 0; potPos < potRows; potPos ++) - { + for (int potPos = 0; potPos < potRows; potPos ++) { QUrl potUrl = m_potModel.itemForIndex(m_potModel.index(potPos, 0, potParent)).url(); int occupiedPos = -1; //TODO: this is slow - for (int poPos = 0; occupiedPos == -1 && poPos < poOccupiedUrls.count(); poPos ++) - { + for (int poPos = 0; occupiedPos == -1 && poPos < poOccupiedUrls.count(); poPos ++) { QUrl& occupiedUrl = poOccupiedUrls[poPos]; if (potUrl.matches(occupiedUrl, QUrl::StripTrailingSlash)) occupiedPos = poPos; @@ -971,30 +909,28 @@ QUrl ProjectModel::poToPot(const QUrl& poPath) const { - if (!(m_poUrl.isParentOf(poPath)||m_poUrl.matches(poPath, QUrl::StripTrailingSlash))) - { - qCWarning(LOKALIZE_LOG)<<"PO path not in project: " << poPath.url(); + if (!(m_poUrl.isParentOf(poPath) || m_poUrl.matches(poPath, QUrl::StripTrailingSlash))) { + qCWarning(LOKALIZE_LOG) << "PO path not in project: " << poPath.url(); return QUrl(); } QString pathToAdd = QDir(m_poUrl.path()).relativeFilePath(poPath.path()); //change ".po" into ".pot" if (pathToAdd.endsWith(QLatin1String(".po"))) //TODO: what about folders ?? - pathToAdd+='t'; + pathToAdd += 't'; QUrl potPath = m_potUrl; - potPath.setPath(potPath.path()%'/'%pathToAdd); + potPath.setPath(potPath.path() % '/' % pathToAdd); //qCDebug(LOKALIZE_LOG) << "ProjectModel::poToPot("<< poPath.pathOrUrl() << +") = " << potPath.pathOrUrl(); return potPath; } QUrl ProjectModel::potToPo(const QUrl& potPath) const { - if (!(m_potUrl.isParentOf(potPath)||m_potUrl.matches(potPath, QUrl::StripTrailingSlash))) - { - qCWarning(LOKALIZE_LOG)<<"POT path not in project: " << potPath.url(); + if (!(m_potUrl.isParentOf(potPath) || m_potUrl.matches(potPath, QUrl::StripTrailingSlash))) { + qCWarning(LOKALIZE_LOG) << "POT path not in project: " << potPath.url(); return QUrl(); } @@ -1005,7 +941,7 @@ pathToAdd = pathToAdd.left(pathToAdd.length() - 1); QUrl poPath = m_poUrl; - poPath.setPath(poPath.path()%'/'%pathToAdd); + poPath.setPath(poPath.path() % '/' % pathToAdd); //qCDebug(LOKALIZE_LOG) << "ProjectModel::potToPo("<< potPath.pathOrUrl() << +") = " << poPath.pathOrUrl(); return poPath; @@ -1019,8 +955,7 @@ { m_doneTimer->stop(); - if (m_dirsWaitingForMetadata.contains(node)) - { + if (m_dirsWaitingForMetadata.contains(node)) { if ((m_activeJob != NULL) && (m_activeNode == node)) m_activeJob->setStatus(-1); @@ -1068,7 +1003,7 @@ QModelIndex item = indexForNode(node); - for (int row=0; row < node->rows.count(); row ++) + for (int row = 0; row < node->rows.count(); row ++) files.append(itemForIndex(index(row, 0, item))); m_activeJob = new UpdateStatsJob(files, this); @@ -1079,24 +1014,21 @@ void ProjectModel::finishMetadataUpdate(UpdateStatsJob* job) { - if (job->m_status == -2) - { + if (job->m_status == -2) { delete job; return; } - if ((m_dirsWaitingForMetadata.contains(m_activeNode)) && (job->m_status == 0)) - { + if ((m_dirsWaitingForMetadata.contains(m_activeNode)) && (job->m_status == 0)) { m_dirsWaitingForMetadata.remove(m_activeNode); //store the results setMetadataForDir(m_activeNode, m_activeJob->m_info); QModelIndex item = indexForNode(m_activeNode); //scan dubdirs - initiate data loading into the model. - for (int row=0; row < m_activeNode->rows.count(); row++) - { + for (int row = 0; row < m_activeNode->rows.count(); row++) { QModelIndex child = index(row, 0, item); if (canFetchMore(child)) @@ -1129,13 +1061,12 @@ void ProjectModel::finishSingleMetadataUpdate(UpdateStatsJob* job) { - if (job->m_status != 0) - { + if (job->m_status != 0) { delete job; return; } - const FileMetaData& info=job->m_info.first(); + const FileMetaData& info = job->m_info.first(); QModelIndex index = indexForUrl(QUrl::fromLocalFile(info.filePath)); if (!index.isValid()) return; @@ -1156,10 +1087,9 @@ int dataCount = data.count(); int rowsCount = node->rows.count(); //Q_ASSERT(dataCount == rowsCount); - if (dataCount != rowsCount) - { + if (dataCount != rowsCount) { m_delayedReloadTimer->start(2000); - qCWarning(LOKALIZE_LOG)<<"dataCount != rowsCount, scheduling full refresh"; + qCWarning(LOKALIZE_LOG) << "dataCount != rowsCount, scheduling full refresh"; return; } @@ -1179,19 +1109,18 @@ void ProjectModel::updateDirStats(ProjectNode* node) { node->calculateDirStats(); - if (node == &m_rootNode) - { + if (node == &m_rootNode) { updateTotalsChanged(); return; } updateDirStats(node->parent); - if (node->parent->rows.count()==0 || node->parent->rows.count()>=node->rowNumber) + if (node->parent->rows.count() == 0 || node->parent->rows.count() >= node->rowNumber) return; QModelIndex index = indexForNode(node); - qCDebug(LOKALIZE_LOG)<parent->rows.count(); - if (index.row()>=node->parent->rows.count()) + qCDebug(LOKALIZE_LOG) << index.row() << node->parent->rows.count(); + if (index.row() >= node->parent->rows.count()) return; QModelIndex topLeft = index.sibling(index.row(), Graph); QModelIndex bottomRight = index.sibling(index.row(), ProjectModelColumnCount - 1); @@ -1203,9 +1132,8 @@ if (model.canFetchMore(index)) return false; - int row=model.rowCount(index); - while (--row>=0) - { + int row = model.rowCount(index); + while (--row >= 0) { if (!updateDone(model.index(row, 0, index), model)) return false; } @@ -1215,8 +1143,7 @@ void ProjectModel::updateTotalsChanged() { bool done = m_dirsWaitingForMetadata.isEmpty(); - if (done) - { + if (done) { done = updateDone(m_poModel.indexForUrl(m_poUrl), m_poModel) && updateDone(m_potModel.indexForUrl(m_potUrl), m_potModel); if (m_rootNode.fuzzyAsPerRole() + m_rootNode.translatedAsPerRole() + m_rootNode.untranslated > 0 && !done) @@ -1262,11 +1189,9 @@ translated_approver = 0; untranslated = 0; - for (int pos = 0; pos < rows.count(); pos++) - { + for (int pos = 0; pos < rows.count(); pos++) { ProjectNode* child = rows.at(pos); - if (child->translated != -1) - { + if (child->translated != -1) { fuzzy += child->fuzzy; fuzzy_reviewer += child->fuzzy_reviewer; fuzzy_approver += child->fuzzy_approver; @@ -1312,18 +1237,13 @@ { FileMetaData m; - if (filePath.endsWith(QLatin1String(".po"))||filePath.endsWith(QLatin1String(".pot"))) - { + if (filePath.endsWith(QLatin1String(".po")) || filePath.endsWith(QLatin1String(".pot"))) { POExtractor extractor; extractor.extract(filePath, m); - } - else if (filePath.endsWith(QLatin1String(".xlf"))||filePath.endsWith(QLatin1String(".xliff"))) - { + } else if (filePath.endsWith(QLatin1String(".xlf")) || filePath.endsWith(QLatin1String(".xliff"))) { XliffExtractor extractor; extractor.extract(filePath, m); - } - else if (filePath.endsWith(QLatin1String(".ts"))) - { + } else if (filePath.endsWith(QLatin1String(".ts"))) { //POExtractor extractor; //extractor.extract(filePath, m); } @@ -1339,12 +1259,12 @@ QSqlQuery queryMain(db); queryMain.exec(QStringLiteral("PRAGMA encoding = \"UTF-8\"")); queryMain.exec(QStringLiteral( - "CREATE TABLE IF NOT EXISTS metadata (" - "filepath INTEGER PRIMARY KEY ON CONFLICT REPLACE, "// AUTOINCREMENT," - //"filepath TEXT UNIQUE ON CONFLICT REPLACE, " - "metadata BLOB, "//XLIFF markup info, see catalog/catalogstring.h catalog/xliff/* - "changedate INTEGER" - ")")); + "CREATE TABLE IF NOT EXISTS metadata (" + "filepath INTEGER PRIMARY KEY ON CONFLICT REPLACE, "// AUTOINCREMENT," + //"filepath TEXT UNIQUE ON CONFLICT REPLACE, " + "metadata BLOB, "//XLIFF markup info, see catalog/catalogstring.h catalog/xliff/* + "changedate INTEGER" + ")")); //queryMain.exec("CREATE INDEX IF NOT EXISTS filepath_index ON metainfo ("filepath)"); } @@ -1386,16 +1306,15 @@ #ifdef NOMETAINFOCACHE return metaData(file.localPath()); #else - QString dbName=QStringLiteral("metainfocache"); - if (!QSqlDatabase::contains(dbName)) - { - QSqlDatabase db=QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"),dbName); + QString dbName = QStringLiteral("metainfocache"); + if (!QSqlDatabase::contains(dbName)) { + QSqlDatabase db = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), dbName); db.setDatabaseName(QStandardPaths::writableLocation(QStandardPaths::DataLocation) % QLatin1Char('/') % dbName % QLatin1String(".sqlite")); - if (Q_UNLIKELY( !db.open() )) + if (Q_UNLIKELY(!db.open())) return metaData(file.localPath()); initDataBase(db); } - QSqlDatabase db=QSqlDatabase::database(dbName); + QSqlDatabase db = QSqlDatabase::database(dbName); if (!db.isOpen()) return metaData(file.localPath()); @@ -1406,64 +1325,60 @@ queryCache.bindValue(0, qHash(file.localPath())); queryCache.exec(); //not using file.time(KFileItem::ModificationTime) because it gives wrong result for files that have just been saved in editor - if (queryCache.next() && QFileInfo(file.localPath()).lastModified()==queryCache.value(2).toDateTime()) - { - result=queryCache.value(1).toByteArray(); - QDataStream stream(&result,QIODevice::ReadOnly); + if (queryCache.next() && QFileInfo(file.localPath()).lastModified() == queryCache.value(2).toDateTime()) { + result = queryCache.value(1).toByteArray(); + QDataStream stream(&result, QIODevice::ReadOnly); FileMetaData info; - stream>>info; + stream >> info; - Q_ASSERT(info.translated==metaData(file.localPath()).translated); + Q_ASSERT(info.translated == metaData(file.localPath()).translated); return info; } FileMetaData m = metaData(file.localPath()); - QDataStream stream(&result,QIODevice::WriteOnly); + QDataStream stream(&result, QIODevice::WriteOnly); //this is synced with ProjectModel::ProjectNode::setFileStats - stream<" //copied from kaboutkdedialog_p.cpp - "You do not have to be a software developer to be a member of the " - "KDE team. You can join the national teams that translate " - "program interfaces. You can provide graphics, themes, sounds, and " - "improved documentation. You decide!" - "

    " - "Visit " - "%1 " - "for information on some projects in which you can participate." - "

    " - "If you need more information or documentation, then a visit to " - "%2 " - "will provide you with what you need.", - QLatin1String("http://community.kde.org/Get_Involved"), - QLatin1String("http://techbase.kde.org/")), welcomeWidget); + "You do not have to be a software developer to be a member of the " + "KDE team. You can join the national teams that translate " + "program interfaces. You can provide graphics, themes, sounds, and " + "improved documentation. You decide!" + "

    " + "Visit " + "%1 " + "for information on some projects in which you can participate." + "

    " + "If you need more information or documentation, then a visit to " + "%2 " + "will provide you with what you need.", + QLatin1String("http://community.kde.org/Get_Involved"), + QLatin1String("http://techbase.kde.org/")), welcomeWidget); about->setAlignment(Qt::AlignCenter); about->setWordWrap(true); about->setOpenExternalLinks(true); about->setTextInteractionFlags(Qt::TextBrowserInteraction); about->setTextFormat(Qt::RichText); QPushButton* conf = new QPushButton(i18n("&Configure Lokalize"), welcomeWidget); - QPushButton* openProject = new QPushButton(i18nc("@action:inmenu","Open project"), welcomeWidget); - QPushButton* createProject = new QPushButton(i18nc("@action:inmenu","Translate software"), welcomeWidget); - QPushButton* createOdfProject = new QPushButton(i18nc("@action:inmenu","Translate OpenDocument"), welcomeWidget); - connect(conf, &QPushButton::clicked, SettingsController::instance(),&SettingsController::showSettingsDialog); + QPushButton* openProject = new QPushButton(i18nc("@action:inmenu", "Open project"), welcomeWidget); + QPushButton* createProject = new QPushButton(i18nc("@action:inmenu", "Translate software"), welcomeWidget); + QPushButton* createOdfProject = new QPushButton(i18nc("@action:inmenu", "Translate OpenDocument"), welcomeWidget); + connect(conf, &QPushButton::clicked, SettingsController::instance(), &SettingsController::showSettingsDialog); connect(openProject, &QPushButton::clicked, this, QOverload<>::of(&ProjectTab::projectOpenRequested)); connect(createProject, &QPushButton::clicked, SettingsController::instance(), &SettingsController::projectCreate); connect(createOdfProject, &QPushButton::clicked, Project::instance(), &Project::projectOdfCreate); - QHBoxLayout* wbtnl=new QHBoxLayout(); + QHBoxLayout* wbtnl = new QHBoxLayout(); wbtnl->addStretch(1); wbtnl->addWidget(conf); wbtnl->addWidget(openProject); @@ -104,23 +104,23 @@ //END setup welcome widget - QWidget* baseWidget=new QWidget(this); + QWidget* baseWidget = new QWidget(this); m_stackedLayout = new QStackedLayout(baseWidget); - QWidget* w=new QWidget(this); + QWidget* w = new QWidget(this); m_stackedLayout->addWidget(welcomeWidget); m_stackedLayout->addWidget(w); connect(Project::instance(), &Project::loaded, this, &ProjectTab::showRealProjectOverview); if (Project::instance()->isLoaded()) //for --project cmd option showRealProjectOverview(); - QVBoxLayout* l=new QVBoxLayout(w); + QVBoxLayout* l = new QVBoxLayout(w); + - m_filterEdit->setClearButtonEnabled(true); m_filterEdit->setPlaceholderText(i18n("Quick search...")); - m_filterEdit->setToolTip(i18nc("@info:tooltip","Activated by Ctrl+L.")%' '%i18nc("@info:tooltip","Accepts regular expressions")); - connect (m_filterEdit, &QLineEdit::textChanged, this, &ProjectTab::setFilterRegExp, Qt::QueuedConnection); - new QShortcut(Qt::CTRL+Qt::Key_L,this,SLOT(setFocus()),0,Qt::WidgetWithChildrenShortcut); + m_filterEdit->setToolTip(i18nc("@info:tooltip", "Activated by Ctrl+L.") % ' ' % i18nc("@info:tooltip", "Accepts regular expressions")); + connect(m_filterEdit, &QLineEdit::textChanged, this, &ProjectTab::setFilterRegExp, Qt::QueuedConnection); + new QShortcut(Qt::CTRL + Qt::Key_L, this, SLOT(setFocus()), 0, Qt::WidgetWithChildrenShortcut); l->addWidget(m_filterEdit); l->addWidget(m_browser); @@ -135,7 +135,7 @@ m_progressBar->setVisible(false); statusBar->insertWidget(ID_STATUS_PROGRESS, m_progressBar, 1); - setXMLFile(QStringLiteral("projectmanagerui.rc"),true); + setXMLFile(QStringLiteral("projectmanagerui.rc"), true); //QAction* action = KStandardAction::find(Project::instance(),SLOT(showTM()),actionCollection()); #define ADD_ACTION_SHORTCUT_ICON(_name,_text,_shortcut,_icon)\ @@ -145,60 +145,60 @@ ac->setDefaultShortcut(action, QKeySequence( _shortcut )); QAction *action; - KActionCollection* ac=actionCollection(); - KActionCategory* nav=new KActionCategory(i18nc("@title actions category","Navigation"), ac); + KActionCollection* ac = actionCollection(); + KActionCategory* nav = new KActionCategory(i18nc("@title actions category", "Navigation"), ac); - ADD_ACTION_SHORTCUT_ICON("go_prev_fuzzyUntr",i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology","Previous not ready"),Qt::CTRL+Qt::SHIFT+Qt::Key_PageUp,"prevfuzzyuntrans") + ADD_ACTION_SHORTCUT_ICON("go_prev_fuzzyUntr", i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology", "Previous not ready"), Qt::CTRL + Qt::SHIFT + Qt::Key_PageUp, "prevfuzzyuntrans") connect(action, &QAction::triggered, this, &ProjectTab::gotoPrevFuzzyUntr); - ADD_ACTION_SHORTCUT_ICON("go_next_fuzzyUntr",i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology","Next not ready"),Qt::CTRL+Qt::SHIFT+Qt::Key_PageDown,"nextfuzzyuntrans") + ADD_ACTION_SHORTCUT_ICON("go_next_fuzzyUntr", i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology", "Next not ready"), Qt::CTRL + Qt::SHIFT + Qt::Key_PageDown, "nextfuzzyuntrans") connect(action, &QAction::triggered, this, &ProjectTab::gotoNextFuzzyUntr); - ADD_ACTION_SHORTCUT_ICON("go_prev_fuzzy",i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology","Previous non-empty but not ready"),Qt::CTRL+Qt::Key_PageUp,"prevfuzzy") + ADD_ACTION_SHORTCUT_ICON("go_prev_fuzzy", i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology", "Previous non-empty but not ready"), Qt::CTRL + Qt::Key_PageUp, "prevfuzzy") connect(action, &QAction::triggered, this, &ProjectTab::gotoPrevFuzzy); - ADD_ACTION_SHORTCUT_ICON("go_next_fuzzy",i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology","Next non-empty but not ready"),Qt::CTRL+Qt::Key_PageDown,"nextfuzzy") + ADD_ACTION_SHORTCUT_ICON("go_next_fuzzy", i18nc("@action:inmenu\n'not ready' means 'fuzzy' in gettext terminology", "Next non-empty but not ready"), Qt::CTRL + Qt::Key_PageDown, "nextfuzzy") connect(action, &QAction::triggered, this, &ProjectTab::gotoNextFuzzy); - ADD_ACTION_SHORTCUT_ICON("go_prev_untrans",i18nc("@action:inmenu","Previous untranslated"),Qt::ALT+Qt::Key_PageUp,"prevuntranslated") + ADD_ACTION_SHORTCUT_ICON("go_prev_untrans", i18nc("@action:inmenu", "Previous untranslated"), Qt::ALT + Qt::Key_PageUp, "prevuntranslated") connect(action, &QAction::triggered, this, &ProjectTab::gotoPrevUntranslated); - ADD_ACTION_SHORTCUT_ICON("go_next_untrans",i18nc("@action:inmenu","Next untranslated"),Qt::ALT+Qt::Key_PageDown,"nextuntranslated") + ADD_ACTION_SHORTCUT_ICON("go_next_untrans", i18nc("@action:inmenu", "Next untranslated"), Qt::ALT + Qt::Key_PageDown, "nextuntranslated") connect(action, &QAction::triggered, this, &ProjectTab::gotoNextUntranslated); - ADD_ACTION_SHORTCUT_ICON("go_prev_templateOnly",i18nc("@action:inmenu","Previous template only"),Qt::CTRL+Qt::Key_Up,"prevtemplate") + ADD_ACTION_SHORTCUT_ICON("go_prev_templateOnly", i18nc("@action:inmenu", "Previous template only"), Qt::CTRL + Qt::Key_Up, "prevtemplate") connect(action, &QAction::triggered, this, &ProjectTab::gotoPrevTemplateOnly); - ADD_ACTION_SHORTCUT_ICON("go_next_templateOnly",i18nc("@action:inmenu","Next template only"),Qt::CTRL+Qt::Key_Down,"nexttemplate") + ADD_ACTION_SHORTCUT_ICON("go_next_templateOnly", i18nc("@action:inmenu", "Next template only"), Qt::CTRL + Qt::Key_Down, "nexttemplate") connect(action, &QAction::triggered, this, &ProjectTab::gotoNextTemplateOnly); - ADD_ACTION_SHORTCUT_ICON("go_prev_transOnly",i18nc("@action:inmenu","Previous translation only"),Qt::ALT+Qt::Key_Up,"prevpo") + ADD_ACTION_SHORTCUT_ICON("go_prev_transOnly", i18nc("@action:inmenu", "Previous translation only"), Qt::ALT + Qt::Key_Up, "prevpo") connect(action, &QAction::triggered, this, &ProjectTab::gotoPrevTransOnly); - ADD_ACTION_SHORTCUT_ICON("go_next_transOnly",i18nc("@action:inmenu","Next translation only"),Qt::ALT+Qt::Key_Down,"nextpo") + ADD_ACTION_SHORTCUT_ICON("go_next_transOnly", i18nc("@action:inmenu", "Next translation only"), Qt::ALT + Qt::Key_Down, "nextpo") connect(action, &QAction::triggered, this, &ProjectTab::gotoNextTransOnly); - action=nav->addAction(QStringLiteral("toggle_translated_files")); - action->setText(i18nc("@action:inmenu","Hide completed items")); - action->setToolTip(i18nc("@action:inmenu","Hide fully translated files and folders")); + action = nav->addAction(QStringLiteral("toggle_translated_files")); + action->setText(i18nc("@action:inmenu", "Hide completed items")); + action->setToolTip(i18nc("@action:inmenu", "Hide fully translated files and folders")); action->setIcon(QIcon::fromTheme("hide_table_row")); action->setCheckable(true); - ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL+Qt::Key_T)); + ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_T)); connect(action, &QAction::triggered, this, &ProjectTab::toggleTranslatedFiles); // ADD_ACTION_SHORTCUT_ICON("edit_find",i18nc("@action:inmenu","Find in files"),Qt::ALT+Qt::Key_Down,"nextpo") //connect(action, &QAction::triggered, this, &ProjectTab::gotoNextTransOnly); - action=nav->addAction(KStandardAction::Find, this, SLOT(searchInFiles())); + action = nav->addAction(KStandardAction::Find, this, SLOT(searchInFiles())); - KActionCategory* proj=new KActionCategory(i18nc("@title actions category","Project"), ac); + KActionCategory* proj = new KActionCategory(i18nc("@title actions category", "Project"), ac); action = proj->addAction(QStringLiteral("project_open"), this, SIGNAL(projectOpenRequested())); action->setText(i18nc("@action:inmenu", "Open project")); action->setIcon(QIcon::fromTheme("project-open")); - - int i=6; - while (--i>ID_STATUS_PROGRESS) - statusBarItems.insert(i,QString()); + + int i = 6; + while (--i > ID_STATUS_PROGRESS) + statusBarItems.insert(i, QString()); } @@ -230,63 +230,60 @@ void ProjectTab::setFilterRegExp() { - QString newPattern=m_filterEdit->text(); - if (m_browser->proxyModel()->filterRegExp().pattern()==newPattern) + QString newPattern = m_filterEdit->text(); + if (m_browser->proxyModel()->filterRegExp().pattern() == newPattern) return; m_browser->proxyModel()->setFilterRegExp(newPattern); - if (newPattern.size()>2) + if (newPattern.size() > 2) m_browser->expandItems(); } void ProjectTab::contextMenuEvent(QContextMenuEvent *event) { - QMenu* menu=new QMenu(this); + QMenu* menu = new QMenu(this); connect(menu, &QMenu::aboutToHide, menu, &QMenu::deleteLater); - if (m_browser->currentIsTranslationFile()) - { - menu->addAction(i18nc("@action:inmenu","Open"),this,SLOT(openFile())); + if (m_browser->currentIsTranslationFile()) { + menu->addAction(i18nc("@action:inmenu", "Open"), this, SLOT(openFile())); menu->addSeparator(); } /*menu.addAction(i18nc("@action:inmenu","Find in files"),this,SLOT(findInFiles())); menu.addAction(i18nc("@action:inmenu","Replace in files"),this,SLOT(replaceInFiles())); menu.addAction(i18nc("@action:inmenu","Spellcheck files"),this,SLOT(spellcheckFiles())); menu.addSeparator(); menu->addAction(i18nc("@action:inmenu","Get statistics for subfolders"),m_browser,SLOT(expandItems())); */ - menu->addAction(i18nc("@action:inmenu","Add to translation memory"),this,SLOT(scanFilesToTM())); + menu->addAction(i18nc("@action:inmenu", "Add to translation memory"), this, SLOT(scanFilesToTM())); - menu->addAction(i18nc("@action:inmenu","Search in files"),this,SLOT(searchInFiles())); + menu->addAction(i18nc("@action:inmenu", "Search in files"), this, SLOT(searchInFiles())); if (QDir(Project::instance()->templatesRoot()).exists()) - menu->addAction(i18nc("@action:inmenu","Search in files (including templates)"),this,SLOT(searchInFilesInclTempl())); + menu->addAction(i18nc("@action:inmenu", "Search in files (including templates)"), this, SLOT(searchInFilesInclTempl())); // else if (Project::instance()->model()->hasChildren(/*m_proxyModel->mapToSource(*/(m_browser->currentIndex())) // ) // { // menu.addSeparator(); // menu.addAction(i18n("Force Scanning"),this,SLOT(slotForceStats())); -// +// // } menu->popup(event->globalPos()); } void ProjectTab::scanFilesToTM() { - TM::scanRecursive(m_browser->selectedItems(),Project::instance()->projectID()); + TM::scanRecursive(m_browser->selectedItems(), Project::instance()->projectID()); } void ProjectTab::searchInFiles(bool templ) { - QStringList files=m_browser->selectedItems(); - if (!templ) - { - QString templatesRoot=Project::instance()->templatesRoot(); - int i=files.size(); - while(--i>=0) - { + QStringList files = m_browser->selectedItems(); + if (!templ) { + QString templatesRoot = Project::instance()->templatesRoot(); + int i = files.size(); + while (--i >= 0) { if (files.at(i).startsWith(templatesRoot)) files.removeAt(i); } @@ -300,49 +297,102 @@ searchInFiles(true); } -void ProjectTab::openFile() {emit fileOpenRequested(m_browser->currentItem());} -void ProjectTab::findInFiles() {emit searchRequested(m_browser->selectedItems());} -void ProjectTab::replaceInFiles() {emit replaceRequested(m_browser->selectedItems());} -void ProjectTab::spellcheckFiles(){emit spellcheckRequested(m_browser->selectedItems());} +void ProjectTab::openFile() +{ + emit fileOpenRequested(m_browser->currentItem()); +} +void ProjectTab::findInFiles() +{ + emit searchRequested(m_browser->selectedItems()); +} +void ProjectTab::replaceInFiles() +{ + emit replaceRequested(m_browser->selectedItems()); +} +void ProjectTab::spellcheckFiles() +{ + emit spellcheckRequested(m_browser->selectedItems()); +} -void ProjectTab::gotoPrevFuzzyUntr() {m_browser->gotoPrevFuzzyUntr();} -void ProjectTab::gotoNextFuzzyUntr() {m_browser->gotoNextFuzzyUntr();} -void ProjectTab::gotoPrevFuzzy() {m_browser->gotoPrevFuzzy();} -void ProjectTab::gotoNextFuzzy() {m_browser->gotoNextFuzzy();} -void ProjectTab::gotoPrevUntranslated() {m_browser->gotoPrevUntranslated();} -void ProjectTab::gotoNextUntranslated() {m_browser->gotoNextUntranslated();} -void ProjectTab::gotoPrevTemplateOnly() {m_browser->gotoPrevTemplateOnly();} -void ProjectTab::gotoNextTemplateOnly() {m_browser->gotoNextTemplateOnly();} -void ProjectTab::gotoPrevTransOnly() {m_browser->gotoPrevTransOnly();} -void ProjectTab::gotoNextTransOnly() {m_browser->gotoNextTransOnly();} +void ProjectTab::gotoPrevFuzzyUntr() +{ + m_browser->gotoPrevFuzzyUntr(); +} +void ProjectTab::gotoNextFuzzyUntr() +{ + m_browser->gotoNextFuzzyUntr(); +} +void ProjectTab::gotoPrevFuzzy() +{ + m_browser->gotoPrevFuzzy(); +} +void ProjectTab::gotoNextFuzzy() +{ + m_browser->gotoNextFuzzy(); +} +void ProjectTab::gotoPrevUntranslated() +{ + m_browser->gotoPrevUntranslated(); +} +void ProjectTab::gotoNextUntranslated() +{ + m_browser->gotoNextUntranslated(); +} +void ProjectTab::gotoPrevTemplateOnly() +{ + m_browser->gotoPrevTemplateOnly(); +} +void ProjectTab::gotoNextTemplateOnly() +{ + m_browser->gotoNextTemplateOnly(); +} +void ProjectTab::gotoPrevTransOnly() +{ + m_browser->gotoPrevTransOnly(); +} +void ProjectTab::gotoNextTransOnly() +{ + m_browser->gotoNextTransOnly(); +} -bool ProjectTab::currentItemIsTranslationFile() const {return m_browser->currentIsTranslationFile();} -void ProjectTab::setCurrentItem(const QString& url){m_browser->setCurrentItem(url);} -QString ProjectTab::currentItem() const {return m_browser->currentItem();} -QStringList ProjectTab::selectedItems() const {return m_browser->selectedItems();} +bool ProjectTab::currentItemIsTranslationFile() const +{ + return m_browser->currentIsTranslationFile(); +} +void ProjectTab::setCurrentItem(const QString& url) +{ + m_browser->setCurrentItem(url); +} +QString ProjectTab::currentItem() const +{ + return m_browser->currentItem(); +} +QStringList ProjectTab::selectedItems() const +{ + return m_browser->selectedItems(); +} void ProjectTab::updateStatusBar(int fuzzy, int translated, int untranslated, bool done) { int total = fuzzy + translated + untranslated; m_currentUnitsCount = total; if (m_progressBar->value() != total && m_legacyUnitsCount > 0) m_progressBar->setValue(total); - if (m_progressBar->maximum() < qMax(total,m_legacyUnitsCount)) - m_progressBar->setMaximum(qMax(total,m_legacyUnitsCount)); + if (m_progressBar->maximum() < qMax(total, m_legacyUnitsCount)) + m_progressBar->setMaximum(qMax(total, m_legacyUnitsCount)); m_progressBar->setVisible(!done); if (done) m_legacyUnitsCount = total; - - statusBarItems.insert(ID_STATUS_TOTAL, i18nc("@info:status message entries","Total: %1", total)); + + statusBarItems.insert(ID_STATUS_TOTAL, i18nc("@info:status message entries", "Total: %1", total)); reflectNonApprovedCount(fuzzy, total); reflectUntranslatedCount(untranslated, total); } void ProjectTab::initStatusBarProgress() { - if (m_legacyUnitsCount > 0) - { + if (m_legacyUnitsCount > 0) { if (m_progressBar->value() != 0) m_progressBar->setValue(0); if (m_progressBar->maximum() != m_legacyUnitsCount) diff --git a/src/project/projectwidget.h b/src/project/projectwidget.h --- a/src/project/projectwidget.h +++ b/src/project/projectwidget.h @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -49,7 +49,7 @@ bool currentIsTranslationFile() const; QSortFilterProxyModel* proxyModel(); - void expandItems(const QModelIndex& parent=QModelIndex()); + void expandItems(const QModelIndex& parent = QModelIndex()); void gotoPrevFuzzyUntr(); void gotoNextFuzzyUntr(); diff --git a/src/project/projectwidget.cpp b/src/project/projectwidget.cpp --- a/src/project/projectwidget.cpp +++ b/src/project/projectwidget.cpp @@ -8,7 +8,7 @@ published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved - by the membership of KDE e.V.), which shall act as a proxy + by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, @@ -49,41 +49,40 @@ class PoItemDelegate: public QStyledItemDelegate { public: - PoItemDelegate(QObject *parent=0); - ~PoItemDelegate(){} - void paint (QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; + PoItemDelegate(QObject *parent = 0); + ~PoItemDelegate() {} + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; private: KColorScheme m_colorScheme; }; PoItemDelegate::PoItemDelegate(QObject *parent) - : QStyledItemDelegate(parent) - , m_colorScheme(QPalette::Normal) + : QStyledItemDelegate(parent) + , m_colorScheme(QPalette::Normal) {} QSize PoItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { - QString text=index.data().toString(); - int lineCount=1; - int nPos=text.indexOf('\n'); - if (nPos==-1) - nPos=text.size(); + QString text = index.data().toString(); + int lineCount = 1; + int nPos = text.indexOf('\n'); + if (nPos == -1) + nPos = text.size(); else - lineCount+=text.count('\n'); + lineCount += text.count('\n'); static QFontMetrics metrics(option.font); - return QSize(metrics.averageCharWidth()*nPos, metrics.height()*lineCount); + return QSize(metrics.averageCharWidth() * nPos, metrics.height() * lineCount); } -void PoItemDelegate::paint (QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const +void PoItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (index.column() != ProjectModel::Graph) - return QStyledItemDelegate::paint(painter,option,index); + return QStyledItemDelegate::paint(painter, option, index); QVariant graphData = index.data(Qt::DisplayRole); - if (Q_UNLIKELY( !graphData.isValid())) - { - painter->fillRect(option.rect,Qt::transparent); + if (Q_UNLIKELY(!graphData.isValid())) { + painter->fillRect(option.rect, Qt::transparent); return; } @@ -93,41 +92,37 @@ int fuzzy = rect.width(); int total = translated + untranslated + fuzzy; - if (total > 0) - { + if (total > 0) { QBrush brush; painter->setPen(Qt::white); QRect myRect(option.rect); myRect.setWidth(option.rect.width() * translated / total); - if (translated) - { - brush=m_colorScheme.foreground(KColorScheme::PositiveText); + if (translated) { + brush = m_colorScheme.foreground(KColorScheme::PositiveText); painter->fillRect(myRect, brush); } myRect.setLeft(myRect.left() + myRect.width()); myRect.setWidth(option.rect.width() * fuzzy / total); - if (fuzzy) - { - brush=m_colorScheme.foreground(KColorScheme::NeutralText); + if (fuzzy) { + brush = m_colorScheme.foreground(KColorScheme::NeutralText); painter->fillRect(myRect, brush); // painter->drawText(myRect,Qt::AlignRight,QString("%1").arg(data.width())); } myRect.setLeft(myRect.left() + myRect.width()); myRect.setWidth(option.rect.width() - myRect.left() + option.rect.left()); if (untranslated) - brush=m_colorScheme.foreground(KColorScheme::NegativeText); + brush = m_colorScheme.foreground(KColorScheme::NegativeText); //esle: paint what is left with the last brush used - blank, positive or neutral painter->fillRect(myRect, brush); // painter->drawText(myRect,Qt::AlignRight,QString("%1").arg(data.top())); - } - else if (total == -1) - painter->fillRect(option.rect,Qt::transparent); + } else if (total == -1) + painter->fillRect(option.rect, Qt::transparent); else if (total == 0) - painter->fillRect(option.rect,QBrush(Qt::gray)); + painter->fillRect(option.rect, QBrush(Qt::gray)); } @@ -137,12 +132,12 @@ class SortFilterProxyModel : public KDirSortFilterProxyModel { public: - SortFilterProxyModel(QObject* parent=0) + SortFilterProxyModel(QObject* parent = 0) : KDirSortFilterProxyModel(parent) { connect(Project::instance()->model(), &ProjectModel::totalsChanged, this, &SortFilterProxyModel::invalidate); } - ~SortFilterProxyModel(){} + ~SortFilterProxyModel() {} void toggleTranslatedFiles(); protected: bool lessThan(const QModelIndex& left, @@ -160,28 +155,28 @@ bool SortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const { - bool result=false; - const QAbstractItemModel* model=sourceModel(); - QModelIndex item=model->index(source_row,0,source_parent); -/* - if (model->hasChildren(item)) - model->fetchMore(item); -*/ + bool result = false; + const QAbstractItemModel* model = sourceModel(); + QModelIndex item = model->index(source_row, 0, source_parent); + /* + if (model->hasChildren(item)) + model->fetchMore(item); + */ if (item.data(ProjectModel::TotalRole) == 0) return false; // Hide rows with no translations if (item.data(ProjectModel::FuzzyUntrCountAllRole) == 0 && m_hideTranslatedFiles) return false; // Hide rows with no untranslated items if the filter is enabled - int i=model->rowCount(item); - while(--i>=0 && !result) - result=filterAcceptsRow(i,item); + int i = model->rowCount(item); + while (--i >= 0 && !result) + result = filterAcceptsRow(i, item); return result || QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); } bool SortFilterProxyModel::lessThan(const QModelIndex& left, - const QModelIndex& right) const + const QModelIndex& right) const { static QCollator collator; // qCWarning(LOKALIZE_LOG)<