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