summaryrefslogtreecommitdiffstats
path: root/src/linguist/lupdate/merge.cpp
blob: f204fc73de8c29c0458cb34481f121b233fd21d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "lupdate.h"

#include "simtexth.h"
#include "translator.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QList>
#include <QtCore/QMap>
#include <QtCore/QStringList>

QT_BEGIN_NAMESPACE

/*
  Augments a Translator with trivially derived translations.

  For example, if "Enabled:" is consistendly translated as "Eingeschaltet:" no
  matter the context or the comment, "Eingeschaltet:" is added as the
  translation of any untranslated "Enabled:" text and is marked Unfinished.

  Returns the number of additional messages that this heuristic translated.
*/

int applySameTextHeuristic(Translator &tor)
{
    QMap<QString, QStringList> translated;
    QMap<QString, bool> avoid; // Want a QTreeSet, in fact
    QList<bool> untranslated(tor.messageCount());
    int inserted = 0;

    for (int i = 0; i < tor.messageCount(); ++i) {
        const TranslatorMessage &msg = tor.message(i);
        if (!msg.isTranslated()) {
            if (msg.type() == TranslatorMessage::Unfinished)
                untranslated[i] = true;
        } else {
            const QString &key = msg.sourceText();
            const auto t = translated.constFind(key);
            if (t != translated.constEnd()) {
                /*
                  The same source text is translated at least two
                  different ways. Do nothing then.
                */
                if (*t != msg.translations()) {
                    translated.remove(key);
                    avoid.insert(key, true);
                }
            } else if (!avoid.contains(key)) {
                translated.insert(key, msg.translations());
            }
        }
    }

    for (int i = 0; i < tor.messageCount(); ++i) {
        if (untranslated[i]) {
            TranslatorMessage &msg = tor.message(i);
            const auto t = translated.constFind(msg.sourceText());
            if (t != translated.constEnd()) {
                msg.setTranslations(*t);
                ++inserted;
            }
        }
    }
    return inserted;
}



/*
  Merges two Translator objects. The first one
  is a set of source texts and translations for a previous version of
  the internationalized program; the second one is a set of fresh
  source texts newly extracted from the source code, without any
  translation yet.
*/

Translator merge(
    const Translator &tor, const Translator &virginTor, const QList<Translator> &aliens,
    UpdateOptions options, QString &err)
{
    int known = 0;
    int neww = 0;
    int obsoleted = 0;
    int similarTextHeuristicCount = 0;

    Translator outTor;
    outTor.setLanguageCode(tor.languageCode());
    outTor.setSourceLanguageCode(tor.sourceLanguageCode());
    outTor.setLocationsType(tor.locationsType());

    /*
      The types of all the messages from the vernacular translator
      are updated according to the virgin translator.
    */
    for (TranslatorMessage m : tor.messages()) {
        TranslatorMessage::Type newType = TranslatorMessage::Finished;

        if (m.sourceText().isEmpty() && m.id().isEmpty()) {
            // context/file comment
            int mvi = virginTor.find(m.context());
            if (mvi >= 0)
                m.setComment(virginTor.constMessage(mvi).comment());
        } else {
            TranslatorMessage::ExtraData extras;
            const TranslatorMessage *mv;
            int mvi = virginTor.find(m);
            if (mvi < 0) {
                if (!(options & HeuristicSimilarText)) {
                  makeObsolete:
                    switch (m.type()) {
                    case TranslatorMessage::Finished:
                        newType = TranslatorMessage::Vanished;
                        obsoleted++;
                        break;
                    case TranslatorMessage::Unfinished:
                        newType = TranslatorMessage::Obsolete;
                        obsoleted++;
                        break;
                    default:
                        newType = m.type();
                        break;
                    }
                    m.clearReferences();
                } else {
                    mvi = virginTor.find(m.context(), m.comment(), m.allReferences());
                    if (mvi < 0) {
                        // did not find it in the virgin, mark it as obsolete
                        goto makeObsolete;
                    }
                    mv = &virginTor.constMessage(mvi);
                    // Do not just accept it if its on the same line number,
                    // but different source text.
                    // Also check if the texts are more or less similar before
                    // we consider them to represent the same message...
                    if (getSimilarityScore(m.sourceText(), mv->sourceText()) < textSimilarityThreshold) {
                        // The virgin and vernacular sourceTexts are so different that we could not find it
                        goto makeObsolete;
                    }
                    // It is just slightly modified, assume that it is the same string

                    extras = mv->extras();

                    // Mark it as unfinished. (Since the source text
                    // was changed it might require re-translating...)
                    newType = TranslatorMessage::Unfinished;
                    ++similarTextHeuristicCount;
                    neww++;
                    goto outdateSource;
                }
            } else {
                mv = &virginTor.message(mvi);
                extras = mv->extras();
                if (!mv->id().isEmpty()
                    && (mv->context() != m.context()
                        || mv->sourceText() != m.sourceText()
                        || mv->comment() != m.comment())) {
                    known++;
                    newType = TranslatorMessage::Unfinished;
                    m.setContext(mv->context());
                    m.setComment(mv->comment());
                    if (mv->sourceText() != m.sourceText()) {
                      outdateSource:
                        m.setOldSourceText(m.sourceText());
                        m.setSourceText(mv->sourceText());
                        const QString &oldpluralsource = m.extra(QLatin1String("po-msgid_plural"));
                        if (!oldpluralsource.isEmpty())
                            extras.insert(QLatin1String("po-old_msgid_plural"), oldpluralsource);
                    }
                } else {
                    switch (m.type()) {
                    case TranslatorMessage::Finished:
                    default:
                        if (m.isPlural() == mv->isPlural()) {
                            newType = TranslatorMessage::Finished;
                        } else {
                            newType = TranslatorMessage::Unfinished;
                        }
                        known++;
                        break;
                    case TranslatorMessage::Unfinished:
                        newType = TranslatorMessage::Unfinished;
                        known++;
                        break;
                    case TranslatorMessage::Vanished:
                        newType = TranslatorMessage::Finished;
                        neww++;
                        break;
                    case TranslatorMessage::Obsolete:
                        newType = TranslatorMessage::Unfinished;
                        neww++;
                        break;
                    }
                }

                // Always get the filename and linenumber info from the
                // virgin Translator, in case it has changed location.
                // This should also enable us to read a file that does not
                // have the <location> element.
                // why not use operator=()? Because it overwrites e.g. userData.
                m.setReferences(mv->allReferences());
                m.setPlural(mv->isPlural());
                m.setExtras(extras);
                m.setExtraComment(mv->extraComment());
                m.setId(mv->id());
            }
        }

        m.setType(newType);
        outTor.append(m);
    }

    /*
      Messages found only in the virgin translator are added to the
      vernacular translator.
    */
    for (const TranslatorMessage &mv : virginTor.messages()) {
        if (mv.sourceText().isEmpty() && mv.id().isEmpty()) {
            if (tor.find(mv.context()) >= 0)
                continue;
        } else {
            if (tor.find(mv) >= 0)
                continue;
            if (options & HeuristicSimilarText) {
                int mi = tor.find(mv.context(), mv.comment(), mv.allReferences());
                if (mi >= 0) {
                    // The similar message found in tor (ts file) must NOT correspond exactly
                    // to an other message is virginTor
                    if (virginTor.find(tor.constMessage(mi)) < 0) {
                        if (getSimilarityScore(tor.constMessage(mi).sourceText(), mv.sourceText())
                                >= textSimilarityThreshold)
                            continue;
                    }
                }
            }
        }
        if (options & NoLocations)
            outTor.append(mv);
        else
            outTor.appendSorted(mv);
        if (!mv.sourceText().isEmpty() || !mv.id().isEmpty())
            ++neww;
    }

    /*
      "Alien" translators can be used to augment the vernacular translator.
    */
    for (const Translator &alf : aliens) {
        for (TranslatorMessage mv : alf.messages()) {
            if (mv.sourceText().isEmpty() || !mv.isTranslated())
                continue;
            int mvi = outTor.find(mv);
            if (mvi >= 0) {
                TranslatorMessage &tm = outTor.message(mvi);
                if (tm.type() != TranslatorMessage::Finished && !tm.isTranslated()) {
                    tm.setTranslations(mv.translations());
                    --neww;
                    ++known;
                }
            } else {
                /*
                 * Don't do simtex search, as the locations are likely to be
                 * completely off anyway, so we'd find nothing.
                 */
                /*
                 * Add the unmatched messages as obsoletes, so the Linguist GUI
                 * will offer them as possible translations.
                 */
                mv.clearReferences();
                mv.setType(mv.type() == TranslatorMessage::Finished
                           ? TranslatorMessage::Vanished : TranslatorMessage::Obsolete);
                if (options & NoLocations)
                    outTor.append(mv);
                else
                    outTor.appendSorted(mv);
                ++known;
                ++obsoleted;
            }
        }
    }

    /*
      The same-text heuristic handles cases where a message has an
      obsolete counterpart with a different context or comment.
    */
    int sameTextHeuristicCount = (options & HeuristicSameText) ? applySameTextHeuristic(outTor) : 0;

    if (options & Verbose) {
        int totalFound = neww + known;
        err += QStringLiteral("    Found %1 source text(s) (%2 new and %3 already existing)\n")
            .arg(totalFound).arg(neww).arg(known);

        if (obsoleted) {
            if (options & NoObsolete) {
                err += QStringLiteral("    Removed %1 obsolete entries\n").arg(obsoleted);
            } else {
                err += QStringLiteral("    Kept %1 obsolete entries\n").arg(obsoleted);
            }
        }

        if (sameTextHeuristicCount)
            err += QStringLiteral("    Same-text heuristic provided %1 translation(s)\n")
                .arg(sameTextHeuristicCount);
        if (similarTextHeuristicCount)
            err += QStringLiteral("    Similar-text heuristic provided %1 translation(s)\n")
                .arg(similarTextHeuristicCount);
    }
    return outTor;
}

QT_END_NAMESPACE