summaryrefslogtreecommitdiff
path: root/src/lang.c
blob: 18c7e3746189ab07d44df575dfa28354cd6bec15 (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
/* Copyright 2021 Jaakko Keränen <jaakko.keranen@iki.fi>

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 THE COPYRIGHT HOLDERS AND 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 THE COPYRIGHT OWNER OR 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 "lang.h"
#include "resources.h"

#include <the_Foundation/sortedarray.h>
#include <the_Foundation/string.h>

iDeclareType(Lang)
iDeclareType(MsgStr)

struct Impl_MsgStr {
    iRangecc id; /* these point to null-terminated strings in resources */
    iRangecc str;
};

int cmp_MsgStr_(const void *e1, const void *e2) {
    const iMsgStr *a = e1, *b = e2;
    return cmpCStrNSc_Rangecc(a->id, b->id.start, size_Range(&b->id), &iCaseSensitive);
}

/*----------------------------------------------------------------------------------------------*/

enum iPluralType {
    none_PluralType,
    notEqualToOne_PluralType,
    polish_PluralType,
    slavic_PluralType,
    oneTwoMany_PluralType,
    oneFewMany_PluralType,
};

struct Impl_Lang {
    iSortedArray *messages;
    enum iPluralType pluralType;
};

static iLang lang_;

static size_t pluralIndex_Lang_(const iLang *d, int n) {
    switch (d->pluralType) {
        case notEqualToOne_PluralType:
            return n != 1;
        case oneTwoMany_PluralType:
            return n == 1 ? 0 : n == 2 ? 1 : 2;
        case oneFewMany_PluralType:
            return n == 1 ? 0 : (n >= 2 && n <= 4) ? 1 : 2;
        case polish_PluralType:
            return n == 1                                                          ? 0
                   : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1
                                                                                   : 2;
        case slavic_PluralType:
            return n % 10 == 1 && n % 100 != 11                                    ? 0
                   : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1
                                                                                   : 2;
        default:
            return 0;
    }
}

static void clear_Lang_(iLang *d) {
    clear_SortedArray(d->messages);
}

static void load_Lang_(iLang *d, const char *id) {
    /* Load compiled language strings from a resource blob. */
    /* TODO: How about an array for these? (id, blob, pluralType) */
    iUnused(id);
    const iBlock *data = equal_CStr(id, "fi")      ? &blobFi_Resources
                       : equal_CStr(id, "fr")      ? &blobFr_Resources
                       : equal_CStr(id, "ru")      ? &blobRu_Resources
                       : equal_CStr(id, "eo")      ? &blobEo_Resources
                       : equal_CStr(id, "es")      ? &blobEs_Resources
                       : equal_CStr(id, "es_MX")   ? &blobEs_MX_Resources
                       : equal_CStr(id, "de")      ? &blobDe_Resources
                       : equal_CStr(id, "gl")      ? &blobGl_Resources
                       : equal_CStr(id, "hu")      ? &blobHu_Embedded
                       : equal_CStr(id, "ia")      ? &blobIa_Resources
                       : equal_CStr(id, "ie")      ? &blobIe_Resources
                       : equal_CStr(id, "isv")     ? &blobIsv_Resources
                       : equal_CStr(id, "pl")      ? &blobPl_Resources
                       : equal_CStr(id, "sk")      ? &blobSk_Resources
                       : equal_CStr(id, "sr")      ? &blobSr_Resources
                       : equal_CStr(id, "tok")     ? &blobTok_Resources
                       : equal_CStr(id, "uk")      ? &blobUk_Resources
                       : equal_CStr(id, "zh_Hans") ? &blobZh_Hans_Resources
                       : equal_CStr(id, "zh_Hant") ? &blobZh_Hant_Resources
                                                   : &blobEn_Resources;
    if (data == &blobRu_Resources || data == &blobSr_Resources || data == &blobUk_Resources) {
        d->pluralType = slavic_PluralType;
    }
    else if (data == &blobIsv_Resources) {
        d->pluralType = oneTwoMany_PluralType;
    }
    else if (data == &blobSk_Resources) {
        d->pluralType = oneFewMany_PluralType;
    }
    else if (data == &blobPl_Resources) {
        d->pluralType = polish_PluralType;
    }
    else if (data == &blobZh_Hans_Resources || data == &blobZh_Hant_Resources ||
             data == &blobTok_Resources) {
        d->pluralType = none_PluralType;
    }
    else {
        d->pluralType = notEqualToOne_PluralType;
    }
    iMsgStr msg;
    for (const char *ptr = constBegin_Block(data); ptr != constEnd_Block(data); ptr++) {
        msg.id.start = ptr;
        while (*++ptr) {}
        msg.id.end = ptr;
        msg.str.start = ++ptr;
        if (*ptr) { /* not empty */
            while (*++ptr) {}
            msg.str.end = ptr;
        }
        else {
            msg.str = msg.id; /* not translated */
        }
        /* Allocate the string. The data has already been sorted. */
//        printf("ID:%s\n", msg.id.start);
        pushBack_Array(&d->messages->values, &msg);
    }
}

void init_Lang(void) {
    iLang *d = &lang_;
    d->messages = new_SortedArray(sizeof(iMsgStr), cmp_MsgStr_);
    setCurrent_Lang("en");
}

void deinit_Lang(void) {
    iLang *d = &lang_;
    clear_Lang_(d);
    delete_SortedArray(d->messages);
}

void setCurrent_Lang(const char *language) {
    iLang *d = &lang_;
    clear_Lang_(d);
    load_Lang_(d, language);
}

static iBool find_Lang_(iRangecc msgId, iRangecc *str_out) {
    const iLang *d = &lang_;
    size_t pos;
    const iMsgStr key = { .id = msgId };
    if (locate_SortedArray(d->messages, &key, &pos)) {
        *str_out = ((const iMsgStr *) at_SortedArray(d->messages, pos))->str;
        return iTrue;
    }
    fprintf(stderr, "[Lang] missing: %s\n", cstr_Rangecc(msgId)); fflush(stderr);
    //    iAssert(iFalse);
    *str_out = msgId;
    return iFalse;
}

iRangecc range_Lang(iRangecc msgId) {
    iRangecc str;
    find_Lang_(msgId, &str);
    return str;
}

const iString *string_Lang(const char *msgId) {
    return collectNewRange_String(range_Lang(range_CStr(msgId)));
}

const char *cstr_Lang(const char *msgId) {
    return range_Lang(range_CStr(msgId)).start; /* guaranteed to be NULL-terminated */
}

static char *pluralId_Lang_(const iLang *d, const char *msgId, int count) {
    const size_t len = strlen(msgId);
    char *pluralId = strdup(msgId);
    pluralId[len - 1] = '0' + pluralIndex_Lang_(d, count);
    return pluralId;
}

const char *cstrCount_Lang(const char *msgId, int count) {
    iAssert(endsWith_Rangecc(range_CStr(msgId), ".n")); /* by convention */
    char *pluralId = pluralId_Lang_(&lang_, msgId, count);
    const char *str = cstr_Lang(pluralId);
    if (str == pluralId) {
        str = msgId; /* not found */
    }
    free(pluralId);
    return str;
}

void translate_Lang(iString *textWithIds) {
    for (const char *pos = cstr_String(textWithIds); *pos; ) {
        iRangecc id;
        id.start = strstr(pos, "${");
        if (!id.start) {
            break;
        }
        id.start += 2;
        id.end = strchr(id.start, '}');
        iAssert(id.end != NULL);
        const size_t idLen = size_Range(&id);
        iRangecc replacement;
        const size_t startPos = id.start - cstr_String(textWithIds) - 2;
        if (find_Lang_(id, &replacement)) {
            /* Replace it. */
            remove_Block(&textWithIds->chars, startPos, idLen + 3);
            insertData_Block(&textWithIds->chars, startPos, replacement.start, size_Range(&replacement));
            pos = cstr_String(textWithIds) + startPos + size_Range(&replacement);
        }
        else {
            remove_Block(&textWithIds->chars, startPos, 1); /* skip on subsequent attempts */
            pos = cstr_String(textWithIds) + startPos + idLen;
        }
    }
}

const char *translateCStr_Lang(const char *textWithIds) {
    if (strstr(textWithIds, "${") == NULL) {
        return textWithIds; /* nothing to replace */
    }
    iString *text = collectNewCStr_String(textWithIds);
    translate_Lang(text);
    return cstr_String(text);
}

const char *formatCStr_Lang(const char *formatMsgId, int count) {
    return format_CStr(cstrCount_Lang(formatMsgId, count), count);
}

const char *formatCStrs_Lang(const char *formatMsgId, size_t count) {
    return format_CStr(cstrCount_Lang(formatMsgId, (int) count), count);
}

const char *format_Lang(const char *formatTextWithIds, ...) {
    iBlock *msg = new_Block(0);
    va_list args;
    va_start(args, formatTextWithIds);
    vprintf_Block(msg, translateCStr_Lang(formatTextWithIds), args);
    va_end(args);
    return cstr_Block(collect_Block(msg));
}