File: WebExtensionLocalization.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (359 lines) | stat: -rw-r--r-- 14,952 bytes parent folder | download | duplicates (6)
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/*
 * Copyright (C) 2024 Igalia, S.L. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "WebExtensionLocalization.h"

#if ENABLE(WK_WEB_EXTENSIONS)

#include "Logging.h"
#include "WebExtension.h"
#include "WebExtensionUtilities.h"
#include <JavaScriptCore/RegularExpression.h>
#include <wtf/Language.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/StringToIntegerConversion.h>
#include <wtf/text/WTFString.h>

namespace WebKit {

static constexpr auto messageKey = "message"_s;
static constexpr auto placeholdersKey = "placeholders"_s;
static constexpr auto placeholderDictionaryContentKey = "content"_s;

static constexpr auto predefinedMessageUILocale = "@@ui_locale"_s;
static constexpr auto predefinedMessageLanguageDirection = "@@bidi_dir"_s;
static constexpr auto predefinedMessageLanguageDirectionReversed = "@@bidi_reversed_dir"_s;
static constexpr auto predefinedMessageTextLeadingEdge = "@@bidi_start_edge"_s;
static constexpr auto predefinedMessageTextTrailingEdge = "@@bidi_end_edge"_s;
static constexpr auto predefinedMessageExtensionID = "@@extension_id"_s;

static constexpr auto predefinedMessageValueLeftToRight = "ltr"_s;
static constexpr auto predefinedMessageValueRightToLeft = "rtl"_s;
static constexpr auto predefinedMessageValueTextEdgeLeft = "left"_s;
static constexpr auto predefinedMessageValueTextEdgeRight = "right"_s;

WebExtensionLocalization::WebExtensionLocalization(WebExtension& webExtension)
{
    auto defaultLocaleString = webExtension.defaultLocale();
    if (defaultLocaleString.isEmpty()) {
        RELEASE_LOG_DEBUG(Extensions, "No default locale provided");
        loadRegionalLocalization(nullptr, nullptr, nullptr, emptyString(), emptyString());
        return;
    }

    RefPtr defaultLocaleJSON = localizationJSONForWebExtension(webExtension, defaultLocaleString);
    if (!defaultLocaleJSON) {
        RELEASE_LOG_DEBUG(Extensions, "No localization found for default locale %s", defaultLocaleString.utf8().data());
        loadRegionalLocalization(nullptr, nullptr, nullptr, emptyString(), emptyString());
        return;
    }

    RELEASE_LOG_DEBUG(Extensions, "Loaded default locale %s", defaultLocaleString.utf8().data());

    auto bestLocaleString = webExtension.bestMatchLocale();
    auto defaultLocaleComponents = parseLocale(defaultLocaleString);
    auto bestLocaleComponents = parseLocale(bestLocaleString);
    auto bestLocaleLanguageOnlyString = bestLocaleComponents.languageCode;

    RELEASE_LOG_DEBUG(Extensions, "Best locale is %s", bestLocaleString.utf8().data());

    RefPtr<JSON::Object> languageJSON;
    if (!bestLocaleLanguageOnlyString.isEmpty() && bestLocaleLanguageOnlyString != defaultLocaleString) {
        languageJSON = localizationJSONForWebExtension(webExtension, bestLocaleLanguageOnlyString);
        if (languageJSON)
            RELEASE_LOG_DEBUG(Extensions, "Loaded language-only locale %s", bestLocaleLanguageOnlyString.utf8().data());
    }

    RefPtr<JSON::Object> regionalJSON;
    if (bestLocaleString != bestLocaleLanguageOnlyString && bestLocaleString != defaultLocaleString) {
        regionalJSON = localizationJSONForWebExtension(webExtension, bestLocaleString);
        if (regionalJSON)
            RELEASE_LOG_DEBUG(Extensions, "Loaded regional locale %s", bestLocaleString.utf8().data());
    }

    loadRegionalLocalization(regionalJSON, languageJSON, defaultLocaleJSON, bestLocaleString);
}

WebExtensionLocalization::WebExtensionLocalization(RefPtr<JSON::Object> localizedJSON, const String& uniqueIdentifier)
{
    ASSERT(!uniqueIdentifier.isEmpty());
    ASSERT(localizedJSON);

    auto localeString = emptyString();
    if (RefPtr predefinedMessages = localizedJSON->getObject(predefinedMessageUILocale))
        localeString = predefinedMessages->getString(messageKey);

    loadRegionalLocalization(localizedJSON, nullptr, nullptr, localeString, uniqueIdentifier);
}

WebExtensionLocalization::WebExtensionLocalization(RefPtr<JSON::Object> regionalLocalization, RefPtr<JSON::Object> languageLocalization, RefPtr<JSON::Object> defaultLocalization, const String& bestLocale, const String& uniqueIdentifier)
{
    loadRegionalLocalization(regionalLocalization, languageLocalization, defaultLocalization, bestLocale, uniqueIdentifier);
}

void WebExtensionLocalization::loadRegionalLocalization(RefPtr<JSON::Object> regionalLocalization, RefPtr<JSON::Object> languageLocalization, RefPtr<JSON::Object> defaultLocalization, const String& bestLocale, const String& uniqueIdentifier)
{
    m_locale = WebCore::Locale::create(AtomString { bestLocale });
    m_localeString = bestLocale;
    m_uniqueIdentifier = uniqueIdentifier;

    RefPtr localizationJSON = predefinedMessages();
    localizationJSON = mergeJSON(localizationJSON, jsonWithLowercaseKeys(regionalLocalization));
    localizationJSON = mergeJSON(localizationJSON, jsonWithLowercaseKeys(languageLocalization));
    localizationJSON = mergeJSON(localizationJSON, jsonWithLowercaseKeys(defaultLocalization));

    ASSERT(localizationJSON);

    m_localizationJSON = localizationJSON;

    return;
}

RefPtr<JSON::Object> WebExtensionLocalization::localizedJSONforJSON(RefPtr<JSON::Object> json)
{
    if (!json)
        return nullptr;

    Ref newObject = JSON::Object::create();

    for (auto& key : json->keys()) {
        auto valueType = json->getValue(key)->type();

        if (valueType == JSON::Value::Type::String)
            newObject->setString(key, localizedStringForString(json->getString(key)));
        else if (valueType == JSON::Value::Type::Array)
            newObject->setArray(key, *localizedArrayForArray(json->getArray(key)));
        else if (valueType == JSON::Value::Type::Object)
            newObject->setObject(key, *localizedJSONforJSON(json->getObject(key)));
        else
            newObject->setValue(key, *json->getValue(key));
    }

    return newObject;
}

String WebExtensionLocalization::localizedStringForKey(String key, Vector<String> placeholders)
{
    if (placeholders.size() > 9)
        return emptyString();

    if (!m_localizationJSON || !m_localizationJSON->size())
        return emptyString();

    if (key.contains("__MSG_"_s)) {
        key = key.substring(6, key.length());
        key = key.substring(0, key.length() - 2);
    }

    RefPtr localizationJSON = m_localizationJSON;
    if (!localizationJSON)
        return emptyString();

    RefPtr stringJSON = localizationJSON->getObject(key.convertToASCIILowercase());
    if (!stringJSON)
        return emptyString();

    auto localizedString = stringJSON->getString(messageKey);
    if (!localizedString.length())
        return emptyString();

    RefPtr namedPlaceholders = jsonWithLowercaseKeys(stringJSON->getObject(placeholdersKey));

    localizedString = stringByReplacingNamedPlaceholdersInString(localizedString, namedPlaceholders);
    localizedString = stringByReplacingPositionalPlaceholdersInString(localizedString, placeholders);

    localizedString = localizedString.impl()->replace("$$"_s, "$"_s);

    return localizedString;
}

RefPtr<JSON::Array> WebExtensionLocalization::localizedArrayForArray(RefPtr<JSON::Array> json)
{
    if (!json)
        return nullptr;

    Ref newArray = JSON::Array::create();

    for (Ref value : *json) {
        auto valueType = value->type();

        if (valueType == JSON::Value::Type::String)
            newArray->pushString(localizedStringForString(value->asString()));
        else if (valueType == JSON::Value::Type::Array)
            newArray->pushArray(*localizedArrayForArray(value->asArray()));
        else if (valueType == JSON::Value::Type::Object)
            newArray->pushObject(*localizedJSONforJSON(value->asObject()));
        else
            newArray->pushValue(WTFMove(value));
    }

    return newArray;
}

String WebExtensionLocalization::localizedStringForString(String sourceString)
{
    String localizedString = sourceString;

    auto localizableStringRegularExpression = JSC::Yarr::RegularExpression("__MSG_([A-Za-z0-9_@]+)__"_s, { });

    int index = 0;
    while (index < static_cast<int>(localizedString.length())) {
        int matchLength;
        index = localizableStringRegularExpression.match(localizedString, index, &matchLength);
        if (index < 0)
            break;

        auto key = localizedString.substring(index, matchLength);
        auto localizedReplacement = localizedStringForKey(key);

        localizedString = makeStringByReplacingAll(localizedString, key, localizedReplacement);

        index += localizedReplacement.length();
    }

    return localizedString;
}

RefPtr<JSON::Object> WebExtensionLocalization::localizationJSONForWebExtension(WebExtension& webExtension, const String& locale)
{
    StringBuilder pathBuilder;
    pathBuilder.append("_locales/"_s);
    pathBuilder.append(locale);
    pathBuilder.append("/messages.json"_s);

    auto path = pathBuilder.toString();

    RefPtr<API::Error> error;
    auto jsonString = webExtension.resourceStringForPath(path, error, WebExtension::CacheResult::No, WebExtension::SuppressNotFoundErrors::Yes);
    if (error) {
        webExtension.recordErrorIfNeeded(error);
        return nullptr;
    }

    RefPtr json = JSON::Value::parseJSON(jsonString);
    return json ? json->asObject() : nullptr;
}

Ref<JSON::Object> WebExtensionLocalization::predefinedMessages()
{
    Ref predefinedMessages = JSON::Object::create();

    auto createMessageKey = [](String messageValue) {
        Ref object = JSON::Object::create();
        object->setString(messageKey, messageValue);
        return object;
    };

    if (m_locale && !m_localeString.isEmpty()) {
        if (m_locale->defaultWritingDirection() == WebCore::Locale::WritingDirection::LeftToRight) {
            predefinedMessages->setObject(predefinedMessageLanguageDirection, createMessageKey(predefinedMessageValueLeftToRight));
            predefinedMessages->setObject(predefinedMessageLanguageDirectionReversed, createMessageKey(predefinedMessageValueRightToLeft));
            predefinedMessages->setObject(predefinedMessageTextLeadingEdge, createMessageKey(predefinedMessageValueTextEdgeLeft));
            predefinedMessages->setObject(predefinedMessageTextTrailingEdge, createMessageKey(predefinedMessageValueTextEdgeRight));
        } else {
            predefinedMessages->setObject(predefinedMessageLanguageDirection, createMessageKey(predefinedMessageValueRightToLeft));
            predefinedMessages->setObject(predefinedMessageLanguageDirectionReversed, createMessageKey(predefinedMessageValueLeftToRight));
            predefinedMessages->setObject(predefinedMessageTextLeadingEdge, createMessageKey(predefinedMessageValueTextEdgeRight));
            predefinedMessages->setObject(predefinedMessageTextTrailingEdge, createMessageKey(predefinedMessageValueTextEdgeLeft));
        }
    }

    if (!m_localeString.isNull())
        predefinedMessages->setObject(predefinedMessageUILocale, createMessageKey(m_localeString));

    if (!m_uniqueIdentifier.isNull())
        predefinedMessages->setObject(predefinedMessageExtensionID, createMessageKey(m_uniqueIdentifier));

    return predefinedMessages;
}

String WebExtensionLocalization::stringByReplacingNamedPlaceholdersInString(String sourceString, RefPtr<JSON::Object> placeholders)
{
    String localizedString = sourceString;

    auto localizableStringRegularExpression = JSC::Yarr::RegularExpression("(?:[^$]|^)(\\$([A-Za-z0-9_@]+)\\$)"_s, { });

    int index = 0;
    while (index < static_cast<int>(localizedString.length())) {
        int matchLength;
        index = localizableStringRegularExpression.match(localizedString, index, &matchLength);
        if (index < 0)
            break;

        auto originalKey = localizedString.substring(index, matchLength);

        if (originalKey.startsWith(' '))
            originalKey = localizedString.substring(index + 1, matchLength - 1);

        auto key = originalKey.trim(isASCIIWhitespace).substring(1, originalKey.length() - 2).convertToASCIILowercase();

        auto localizedReplacement = placeholders->getObject(key) ? placeholders->getObject(key)->getString(placeholderDictionaryContentKey) : emptyString();

        localizedString = makeStringByReplacingAll(localizedString, originalKey, localizedReplacement);

        index += localizedReplacement.length();
    }

    return localizedString;
}

String WebExtensionLocalization::stringByReplacingPositionalPlaceholdersInString(String sourceString, Vector<String> placeholders)
{
    auto localizedString = sourceString;

    auto localizableStringRegularExpression = JSC::Yarr::RegularExpression("(?:[^$]|^)(\\$([0-9]))"_s, { });

    int index = 0;
    while (index < static_cast<int>(localizedString.length())) {
        int matchLength;
        index = localizableStringRegularExpression.match(localizedString, index, &matchLength);
        if (index < 0)
            break;

        auto originalKey = localizedString.substring(index, matchLength).trim(isASCIIWhitespace<UChar>);
        auto key = originalKey.substring(1, originalKey.length());
        auto keyInteger = parseInteger<size_t>(key);

        String replacement;
        if (keyInteger && placeholders.size() && *keyInteger <= placeholders.size() && keyInteger > 0)
            replacement = placeholders[*keyInteger - 1];
        else
            replacement = emptyString();

        localizedString = makeStringByReplacingAll(localizedString, originalKey, replacement);

        if (!matchLength)
            break;

        index += replacement.length() + 2;
    }

    return localizedString;
}

} // namespace WebKit

#endif // ENABLE(WK_WEB_EXTENSIONS)