summaryrefslogtreecommitdiff
path: root/indra/llui/llemojidictionary.cpp
blob: 1ee97ea2d215b6436d93c65fb272a430e04114a6 (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
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/**
* @file llemojidictionary.cpp
* @brief Implementation of LLEmojiDictionary
*
* $LicenseInfo:firstyear=2014&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2014, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
* $/LicenseInfo$
*/

#include "linden_common.h"

#include "lldir.h"
#include "llemojidictionary.h"
#include "llsdserialize.h"

#include <boost/algorithm/string.hpp>
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/algorithm/transform.hpp>

// ============================================================================
// Constants
//

static const std::string SKINNED_EMOJI_FILENAME("emoji_characters.xml");
static const std::string SKINNED_CATEGORY_FILENAME("emoji_categories.xml");
static const std::string COMMON_GROUP_FILENAME("emoji_groups.xml");
static const std::string GROUP_NAME_ALL("all");
static const std::string GROUP_NAME_OTHERS("others");
static const std::string GROUP_NAME_SKIP("skip");

// ============================================================================
// Helper functions
//

template<class T>
std::list<T> llsd_array_to_list(const LLSD& sd, std::function<void(T&)> mutator = {});

template<>
std::list<std::string> llsd_array_to_list(const LLSD& sd, std::function<void(std::string&)> mutator)
{
    std::list<std::string> result;
    for (LLSD::array_const_iterator it = sd.beginArray(), end = sd.endArray(); it != end; ++it)
    {
        const LLSD& entry = *it;
        if (!entry.isString())
            continue;

        result.push_back(entry.asStringRef());
        if (mutator)
        {
            mutator(result.back());
        }
    }
    return result;
}

struct emoji_filter_base
{
    emoji_filter_base(const std::string& needle)
    {
        // Search without the colon (if present) so the user can type ':food' and see all emojis in the 'Food' category
        mNeedle = (boost::starts_with(needle, ":")) ? needle.substr(1) : needle;
        LLStringUtil::toLower(mNeedle);
    }

protected:
    std::string mNeedle;
};

struct emoji_filter_shortcode_or_category_contains : public emoji_filter_base
{
    emoji_filter_shortcode_or_category_contains(const std::string& needle) : emoji_filter_base(needle) {}

    bool operator()(const LLEmojiDescriptor& descr) const
    {
        for (const auto& short_code : descr.ShortCodes)
        {
            if (boost::icontains(short_code, mNeedle))
                return true;
        }

        if (boost::icontains(descr.Category, mNeedle))
            return true;

        return false;
    }
};

std::string LLEmojiDescriptor::getShortCodes() const
{
    std::string result;
    for (const std::string& shortCode : ShortCodes)
    {
        if (!result.empty())
        {
            result += ", ";
        }
        result += shortCode;
    }
    return result;
}

// ============================================================================
// LLEmojiDictionary class
//

LLEmojiDictionary::LLEmojiDictionary()
{
}

// static
void LLEmojiDictionary::initClass()
{
    LLEmojiDictionary* pThis = &LLEmojiDictionary::initParamSingleton();

    pThis->loadTranslations();
    pThis->loadGroups();
    pThis->loadEmojis();
}

LLWString LLEmojiDictionary::findMatchingEmojis(const std::string& needle) const
{
    LLWString result;
    boost::transform(mEmojis | boost::adaptors::filtered(emoji_filter_shortcode_or_category_contains(needle)),
                     std::back_inserter(result), [](const auto& descr) { return descr.Character; });
    return result;
}

const LLEmojiDescriptor* LLEmojiDictionary::getDescriptorFromEmoji(llwchar emoji) const
{
    const auto it = mEmoji2Descr.find(emoji);
    return (mEmoji2Descr.end() != it) ? it->second : nullptr;
}

const LLEmojiDescriptor* LLEmojiDictionary::getDescriptorFromShortCode(const std::string& short_code) const
{
    const auto it = mShortCode2Descr.find(short_code);
    return (mShortCode2Descr.end() != it) ? it->second : nullptr;
}

std::string LLEmojiDictionary::getNameFromEmoji(llwchar ch) const
{
    const auto it = mEmoji2Descr.find(ch);
    return (mEmoji2Descr.end() != it) ? it->second->ShortCodes.front() : LLStringUtil::null;
}

bool LLEmojiDictionary::isEmoji(llwchar ch) const
{
    // Currently used codes: A9,AE,203C,2049,2122,...,2B55,3030,303D,3297,3299,1F004,...,1FAF6
    if (ch == 0xA9 || ch == 0xAE || (ch >= 0x2000 && ch < 0x3300) || (ch >= 0x1F000 && ch < 0x20000))
    {
        return mEmoji2Descr.find(ch) != mEmoji2Descr.end();
    }

    return false;
}

void LLEmojiDictionary::loadTranslations()
{
    std::vector<std::string> filenames = gDirUtilp->findSkinnedFilenames(LLDir::XUI, SKINNED_CATEGORY_FILENAME, LLDir::CURRENT_SKIN);
    if (filenames.empty())
    {
        LL_WARNS() << "Emoji file categories not found" << LL_ENDL;
        return;
    }

    const std::string filename = filenames.back();
    llifstream file(filename.c_str());
    if (!file.is_open())
    {
        LL_WARNS() << "Emoji file categories failed to open" << LL_ENDL;
        return;
    }

    LL_DEBUGS() << "Loading emoji categories file at " << filename << LL_ENDL;

    LLSD data;
    LLSDSerialize::fromXML(data, file);
    if (data.isUndefined())
    {
        LL_WARNS() << "Emoji file categories missing or ill-formed" << LL_ENDL;
        return;
    }

    // Register translations for all categories
    for (LLSD::array_const_iterator it = data.beginArray(), end = data.endArray(); it != end; ++it)
    {
        const LLSD& sd = *it;
        const std::string& name = sd["Name"].asStringRef();
        const std::string& category = sd["Category"].asStringRef();
        if (!name.empty() && !category.empty())
        {
            mTranslations[name] = category;
        }
        else
        {
            LL_WARNS() << "Skipping invalid emoji category '" << name << "' => '" << category << "'" << LL_ENDL;
        }
    }
}

void LLEmojiDictionary::loadGroups()
{
    const std::string filename = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, COMMON_GROUP_FILENAME);
    llifstream file(filename.c_str());
    if (!file.is_open())
    {
        LL_WARNS() << "Emoji file groups failed to open" << LL_ENDL;
        return;
    }

    LL_DEBUGS() << "Loading emoji groups file at " << filename << LL_ENDL;

    LLSD data;
    LLSDSerialize::fromXML(data, file);
    if (data.isUndefined())
    {
        LL_WARNS() << "Emoji file groups missing or ill-formed" << LL_ENDL;
        return;
    }

    mGroups.clear();
    // Add group "all"
    mGroups.emplace_back();
    // https://www.compart.com/en/unicode/U+1F50D
    mGroups.front().Character = 0x1F50D;
    // https://www.compart.com/en/unicode/U+1F302
    llwchar iconOthers = 0x1F302;

    // Register all groups
    for (LLSD::array_const_iterator it = data.beginArray(), end = data.endArray(); it != end; ++it)
    {
        const LLSD& sd = *it;
        const std::string& name = sd["Name"].asStringRef();
        if (name == GROUP_NAME_ALL)
        {
            mGroups.front().Character = loadIcon(sd);
        }
        else if (name == GROUP_NAME_OTHERS)
        {
            iconOthers = loadIcon(sd);
        }
        else if (name == GROUP_NAME_SKIP)
        {
            mSkipCategories = loadCategories(sd);
            translateCategories(mSkipCategories);
        }
        else
        {
            // Add new group
            mGroups.emplace_back();
            LLEmojiGroup& group = mGroups.back();
            group.Character = loadIcon(sd);
            group.Categories = loadCategories(sd);
            translateCategories(group.Categories);

            for (const std::string& category : group.Categories)
            {
                mCategory2Group.insert(std::make_pair(category, &group));
            }
        }
    }

    // Add group "others"
    mGroups.emplace_back();
    mGroups.back().Character = iconOthers;
}

void LLEmojiDictionary::loadEmojis()
{
    std::vector<std::string> filenames = gDirUtilp->findSkinnedFilenames(LLDir::XUI, SKINNED_EMOJI_FILENAME, LLDir::CURRENT_SKIN);
    if (filenames.empty())
    {
        LL_WARNS() << "Emoji file characters not found" << LL_ENDL;
        return;
    }

    const std::string filename = filenames.back();
    llifstream file(filename.c_str());
    if (!file.is_open())
    {
        LL_WARNS() << "Emoji file characters failed to open" << LL_ENDL;
        return;
    }

    LL_DEBUGS() << "Loading emoji characters file at " << filename << LL_ENDL;

    LLSD data;
    LLSDSerialize::fromXML(data, file);
    if (data.isUndefined())
    {
        LL_WARNS() << "Emoji file characters missing or ill-formed" << LL_ENDL;
        return;
    }

    for (LLSD::array_const_iterator it = data.beginArray(), end = data.endArray(); it != end; ++it)
    {
        const LLSD& sd = *it;

        llwchar icon = loadIcon(sd);
        if (!icon)
        {
            LL_WARNS() << "Skipping invalid emoji descriptor (no icon)" << LL_ENDL;
            continue;
        }

        std::list<std::string> categories = loadCategories(sd);
        if (categories.empty())
        {
            LL_WARNS() << "Skipping invalid emoji descriptor (no categories)" << LL_ENDL;
            continue;
        }

        std::string category = categories.front();

        if (std::find(mSkipCategories.begin(), mSkipCategories.end(), category) != mSkipCategories.end())
        {
            // This category is listed for skip
            continue;
        }

        std::list<std::string> shortCodes = loadShortCodes(sd);
        if (shortCodes.empty())
        {
            LL_WARNS() << "Skipping invalid emoji descriptor (no shortCodes)" << LL_ENDL;
            continue;
        }

        if (mCategory2Group.find(category) == mCategory2Group.end())
        {
            // Add unknown category to "others" group
            mGroups.back().Categories.push_back(category);
            mCategory2Group.insert(std::make_pair(category, &mGroups.back()));
        }

        mEmojis.emplace_back();
        LLEmojiDescriptor& emoji = mEmojis.back();
        emoji.Character = icon;
        emoji.Category = category;
        emoji.ShortCodes = std::move(shortCodes);

        mEmoji2Descr.insert(std::make_pair(icon, &emoji));
        mCategory2Descrs[category].push_back(&emoji);
        for (const std::string& shortCode : emoji.ShortCodes)
        {
            mShortCode2Descr.insert(std::make_pair(shortCode, &emoji));
        }
    }
}

llwchar LLEmojiDictionary::loadIcon(const LLSD& sd)
{
    // We don't currently support character composition
    const LLWString icon = utf8str_to_wstring(sd["Character"].asString());
    return (1 == icon.size()) ? icon[0] : L'\0';
}

std::list<std::string> LLEmojiDictionary::loadCategories(const LLSD& sd)
{
    static const std::string key("Categories");
    return llsd_array_to_list<std::string>(sd[key]);
}

std::list<std::string> LLEmojiDictionary::loadShortCodes(const LLSD& sd)
{
    static const std::string key("ShortCodes");
    auto toLower = [](std::string& str) { LLStringUtil::toLower(str); };
    return llsd_array_to_list<std::string>(sd[key], toLower);
}

void LLEmojiDictionary::translateCategories(std::list<std::string>& categories)
{
    for (std::string& category : categories)
    {
        auto it = mTranslations.find(category);
        if (it != mTranslations.end())
        {
            category = it->second;
        }
    }
}

// ============================================================================