summaryrefslogtreecommitdiff
path: root/src/ui/translation.c
blob: e5059f3865293be596ca8c20fbe99e342bc9e9f6 (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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
/* 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 "translation.h"

#include "app.h"
#include "defs.h"
#include "gmdocument.h"
#include "ui/command.h"
#include "ui/documentwidget.h"
#include "ui/labelwidget.h"
#include "ui/paint.h"
#include "ui/util.h"

#include <the_Foundation/regexp.h>
#include <SDL_timer.h>
#include <math.h>

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

iDeclareWidgetClass(TranslationProgressWidget)
iDeclareObjectConstruction(TranslationProgressWidget)

iDeclareType(Sprite)

struct Impl_Sprite {
    iInt2 pos;
    iInt2 size;
    int color;
    int xoff;
    iString text;
};

struct Impl_TranslationProgressWidget {
    iWidget widget;
    uint32_t startTime;
    int font;
    iArray sprites;
    iString message;
};

void init_TranslationProgressWidget(iTranslationProgressWidget *d) {
    iWidget *w = &d->widget;
    init_Widget(w);
    setId_Widget(w, "xlt.progress");
    init_Array(&d->sprites, sizeof(iSprite));
    d->startTime = SDL_GetTicks();
    init_String(&d->message);
    /* Set up some letters to animate. */
    const char *chars = "ARGOS";
    const size_t n = strlen(chars);
    resize_Array(&d->sprites, n);
    d->font = uiContentBold_FontId;
    const int width = lineHeight_Text(d->font);
    const int gap = gap_Text / 2;
    int x = (int) (n * width + (n - 1) * gap) / -2;
    const int y = -lineHeight_Text(d->font) / 2;
    for (size_t i = 0; i < n; i++) {
        iSprite *spr = at_Array(&d->sprites, i);
        spr->pos = init_I2(x, y);
        spr->color = 0;
        init_String(&spr->text);
        appendChar_String(&spr->text, chars[i]);
        spr->xoff = (width - advanceRange_Text(d->font, range_String(&spr->text)).x) / 2;
        spr->size = init_I2(width, lineHeight_Text(d->font));
        x += width + gap;
    }
}

void deinit_TranslationProgressWidget(iTranslationProgressWidget *d) {
    deinit_String(&d->message);
    iForEach(Array, i, &d->sprites) {
        iSprite *spr = i.value;
        deinit_String(&spr->text);
    }
    deinit_Array(&d->sprites);
}

iDefineObjectConstruction(TranslationProgressWidget)

static void draw_TranslationProgressWidget_(const iTranslationProgressWidget *d) {
    const iWidget *w = &d->widget;
    const float t = (float) (SDL_GetTicks() - d->startTime) / 1000.0f;
    const iRect bounds = bounds_Widget(w);
    if (!isEmpty_String(&d->message)) {
        drawCentered_Text(
            uiLabel_FontId, bounds, iFalse, uiText_ColorId, "%s", cstr_String(&d->message));
        return;
    }
    iPaint p;
    init_Paint(&p);
    const iInt2 mid = mid_Rect(bounds);
    SDL_SetRenderDrawBlendMode(renderer_Window(get_Window()), SDL_BLENDMODE_BLEND);
    iConstForEach(Array, i, &d->sprites) {
        const int index = (int) index_ArrayConstIterator(&i);
        const float angle = (float) index;
        const iSprite *spr = i.value;
        const float opacity = iClamp(t - index * 0.5f, 0.0, 1.0f);
        int bg = uiBackgroundSelected_ColorId;
        int fg = uiTextSelected_ColorId;
        iInt2 pos = add_I2(mid, spr->pos);
        float t2 = sin(0.2f * t);
        pos.y += sin(angle + t) * spr->size.y * t2 * t2 * iClamp(t * 0.25f - 0.3f, 0.0f, 1.0f);
        if (bg >= 0) {
            p.alpha = opacity * 255;
            fillRect_Paint(&p, (iRect){ pos, spr->size }, bg);
        }
        if (fg >= 0) {
            setOpacity_Text(opacity * 2);
            drawRange_Text(d->font, addX_I2(pos, spr->xoff), fg, range_String(&spr->text));
        }
    }
    setOpacity_Text(1.0f);
    SDL_SetRenderDrawBlendMode(renderer_Window(get_Window()), SDL_BLENDMODE_NONE);
}

static iBool processEvent_TranslationProgressWidget_(iTranslationProgressWidget *d,
                                                     const SDL_Event *ev) {
    iUnused(d, ev);
    return iFalse;
}

iBeginDefineSubclass(TranslationProgressWidget, Widget)
    .draw         = (iAny *) draw_TranslationProgressWidget_,
    .processEvent = (iAny *) processEvent_TranslationProgressWidget_,
 iEndDefineSubclass(TranslationProgressWidget)

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

iDefineTypeConstructionArgs(Translation, (iDocumentWidget *doc), doc)

static const char *   translationServiceHost = "xlt.skyjake.fi";
static const uint16_t translationServicePort = 443;

//static const char *doubleArrowSymbol    = "\U0001f192"; //"\u20e2"; /* prevent getting mangled */
//static const char *tripleBacktickSymbol = "\U0001f1a9"; //\u20e3";
//static const char *h1Symbol             = "\U0001f19d";
//static const char *h2Symbol             = "\U0001f19e";
//static const char *h3Symbol             = "\U0001f19f";
//static const char *bulletSymbol         = "\n\U0001f196";

static iString *quote_String_(const iString *d) {
    iString *quot = new_String();
    iConstForEach(String, i, d) {
        const iChar ch = i.value;
        if (ch == '"') {
            appendCStr_String(quot, "\\\"");
        }
        else if (ch == '\\') {
            appendCStr_String(quot, "\\\\");
        }
        else if (ch == '\n') {
            appendCStr_String(quot, "\\n");
        }
        else if (ch == '\r') {
            appendCStr_String(quot, "\\r");
        }
        else if (ch == '\t') {
            appendCStr_String(quot, "\\t");
        }
        else if (ch >= 0x80) {
            if ((ch >= 0xD800 && ch < 0xE000) || ch >= 0x10000) {
                /* TODO: Add a helper function? */
                /* UTF-16 surrogate pair */
                iString *chs = newUnicodeN_String(&ch, 1);
                iBlock *u16 = toUtf16_String(chs);
                delete_String(chs);
                const uint16_t *ch16 = constData_Block(u16);
                appendFormat_String(quot, "\\u%04x\\u%04x", ch16[0], ch16[1]);
            }
            else {
                appendFormat_String(quot, "\\u%04x", ch);
            }
        }
        else {
            appendChar_String(quot, ch);
        }
    }
    return quot;
}

static iString *unquote_String_(const iString *d) {
    iString *unquot = new_String();
    iConstForEach(String, i, d) {
        const iChar ch = i.value;
        if (ch == '\\') {
            next_StringConstIterator(&i);
            const iChar esc = i.value;
            if (esc == '\\') {
                appendChar_String(unquot, esc);
            }
            else if (esc == 'n') {
                appendChar_String(unquot, '\n');
            }
            else if (esc == 'r') {
                appendChar_String(unquot, '\r');
            }
            else if (esc == 't') {
                appendChar_String(unquot, '\t');
            }
            else if (esc == '"') {
                appendChar_String(unquot, '"');
            }
            else if (esc == 'u') {
                char digits[5];
                iZap(digits);
                for (size_t j = 0; j < 4; j++) {
                    next_StringConstIterator(&i);
                    digits[j] = *i.pos;
                }
                uint16_t ch16[2] = { strtoul(digits, NULL, 16), 0 };
                if (ch16[0] < 0xD800 || ch16[0] >= 0xE000) {
                    appendChar_String(unquot, ch16[0]);
                }
                else {
                    /* UTF-16 surrogate pair */
                    next_StringConstIterator(&i);
                    next_StringConstIterator(&i);
                    iZap(digits);
                    for (size_t j = 0; j < 4; j++) {
                        next_StringConstIterator(&i);
                        digits[j] = *i.pos;
                    }
                    ch16[1] = strtoul(digits, NULL, 16);
                    iString *u16 = newUtf16N_String(ch16, 2);
                    append_String(unquot, u16);
                    delete_String(u16);
                }
            }
            else {
                iAssert(0);
            }
        }
        else {
            appendChar_String(unquot, ch);
        }
    }
    return unquot;
}

static void finished_Translation_(iTlsRequest *d, iTlsRequest *req) {
    iUnused(req);
    postCommandf_App("translation.finished ptr:%p", userData_Object(d));
}

void init_Translation(iTranslation *d, iDocumentWidget *doc) {
    d->dlg       = makeTranslation_Widget(as_Widget(doc));
    d->startTime = 0;
    d->doc       = doc; /* owner */
    d->request   = new_TlsRequest();
    d->timer     = 0;
    init_Array(&d->lineTypes, sizeof(int));
    setUserData_Object(d->request, d->doc);
    setHost_TlsRequest(d->request,
                       collectNewCStr_String(translationServiceHost),
                       translationServicePort);
    iConnect(TlsRequest, d->request, finished, d->request, finished_Translation_);
}

void deinit_Translation(iTranslation *d) {
    if (d->timer) {
        SDL_RemoveTimer(d->timer);
    }
    cancel_TlsRequest(d->request);
    iRelease(d->request);
    destroy_Widget(d->dlg);
    deinit_Array(&d->lineTypes);
}

static uint32_t animate_Translation_(uint32_t interval, iAny *ptr) {
    postCommandf_App("translation.update ptr:%p", ((iTranslation *) ptr)->doc);
    return interval;
}

void submit_Translation(iTranslation *d) {
    /* Check the selected languages from the dialog. */
    const char *idFrom = languageId_String(text_LabelWidget(findChild_Widget(d->dlg, "xlt.from")));
    const char *idTo   = languageId_String(text_LabelWidget(findChild_Widget(d->dlg, "xlt.to")));
    iAssert(status_TlsRequest(d->request) != submitted_TlsRequestStatus);
    iBlock *json = collect_Block(new_Block(0));
    iString *docSrc = collectNew_String();
    /* TODO: Strip all markup and remember it. These are reapplied when reading response. */ {
        iRangecc line = iNullRange;
        while (nextSplit_Rangecc(
            range_String(source_GmDocument(document_DocumentWidget(d->doc))), "\n", &line)) {
            iRangecc cleanLine = trimmed_Rangecc(line);
            const int lineType = lineType_Rangecc(cleanLine);
            pushBack_Array(&d->lineTypes, &lineType);
            if (lineType == link_GmLineType) {
                cleanLine.start += 2; /* skip over the => */
            }
            else {
                trimLine_Rangecc(&cleanLine, lineType, iTrue); /* removes the prefix */
            }
            if (!isEmpty_String(docSrc)) {
                appendCStr_String(docSrc, "\n");
            }
            appendRange_String(docSrc, cleanLine);
        }
    }
//    replace_String(docSrc, "=>", doubleArrowSymbol);
//    replace_String(docSrc, "```", tripleBacktickSymbol);
//    replace_String(docSrc, "###", h3Symbol);
//    replace_String(docSrc, "##", h2Symbol);
//    replace_String(docSrc, "#", h1Symbol);
//    replace_String(docSrc, "\n*", bulletSymbol);
    printf_Block(json,
                 "{\"q\":\"%s\",\"source\":\"%s\",\"target\":\"%s\"}",
                 cstrCollect_String(quote_String_(docSrc)),
                 idFrom,
                 idTo);
    iBlock *msg = collect_Block(new_Block(0));
    printf_Block(msg, "POST /translate HTTP/1.1\r\n"
                      "Host: xlt.skyjake.fi\r\n"
                      "Connection: close\r\n"
                      "Content-Type: application/json; charset=utf-8\r\n"
                      "Content-Length: %zu\r\n\r\n", size_Block(json));
    append_Block(msg, json);
    setContent_TlsRequest(d->request, msg);
    submit_TlsRequest(d->request);
    d->startTime = SDL_GetTicks();
    d->timer = SDL_AddTimer(1000 / 30, animate_Translation_, d);
}

static void setFailed_Translation_(iTranslation *d, const char *msg) {
    iTranslationProgressWidget *prog = findChild_Widget(d->dlg, "xlt.progress");
    if (prog && isEmpty_String(&prog->message)) {
        setCStr_String(&prog->message, msg);
    }
}

static iBool processResult_Translation_(iTranslation *d) {
    SDL_RemoveTimer(d->timer);
    d->timer = 0;
    if (status_TlsRequest(d->request) == error_TlsRequestStatus) {
        setFailed_Translation_(d, explosion_Icon "  Request Failed");
        return iFalse;
    }
    iBlock *resultData = collect_Block(readAll_TlsRequest(d->request));
    printf("result(%zu):\n%s\n", size_Block(resultData), cstr_Block(resultData));
    fflush(stdout);
    iRegExp *pattern = iClob(new_RegExp(".*translatedText\":\"(.*)\"\\}", caseSensitive_RegExpOption));
    iRegExpMatch m;
    init_RegExpMatch(&m);
    if (matchRange_RegExp(pattern, range_Block(resultData), &m)) {
        iString *translation = unquote_String_(collect_String(captured_RegExpMatch(&m, 1)));
        iString *marked = collectNew_String();
        iRangecc line;
        size_t lineIndex = 0;
        while (nextSplit_Rangecc(range_String(translation), "\n", &line)) {
            iRangecc cleanLine = trimmed_Rangecc(line);
            if (!isEmpty_String(marked)) {
                appendCStr_String(marked, "\n");
            }
            if (lineIndex < size_Array(&d->lineTypes)) {
                switch (value_Array(&d->lineTypes, lineIndex, int)) {
                    case bullet_GmLineType:
                        appendCStr_String(marked, "* ");
                        break;
                    case link_GmLineType:
                        appendCStr_String(marked, "=> ");
                        break;
                    case quote_GmLineType:
                        appendCStr_String(marked, "> ");
                        break;
                    case preformatted_GmLineType:
                        appendCStr_String(marked, "```");
                        break;
                    case heading1_GmLineType:
                        appendCStr_String(marked, "# ");
                        break;
                    case heading2_GmLineType:
                        appendCStr_String(marked, "## ");
                        break;
                    case heading3_GmLineType:
                        appendCStr_String(marked, "### ");
                        break;
                    default:
                        break;
                }
            }
            appendRange_String(marked, cleanLine);
            lineIndex++;
        }
//        replace_String(translation, tripleBacktickSymbol, "```");
//        replace_String(translation, doubleArrowSymbol, "=>");
//        replace_String(translation, h3Symbol, "### ");
//        replace_String(translation, h2Symbol, "## ");
//        replace_String(translation, h1Symbol, "# ");
//        replace_String(translation, bulletSymbol, "\n* ");
        setSource_DocumentWidget(d->doc, marked);
        postCommand_App("sidebar.update");
        delete_String(translation);
    }
    else {
        setFailed_Translation_(d, unhappy_Icon "  Service Unavailable");
        return iFalse;
    }
    return iTrue;
}

static iLabelWidget *acceptButton_Translation_(const iTranslation *d) {
    return (iLabelWidget *) lastChild_Widget(findChild_Widget(d->dlg, "dialogbuttons"));
}

iBool handleCommand_Translation(iTranslation *d, const char *cmd) {
    iWidget *w = as_Widget(d->doc);
    if (equalWidget_Command(cmd, w, "translation.submit")) {
        if (status_TlsRequest(d->request) == initialized_TlsRequestStatus) {
            iWidget *langs = findChild_Widget(d->dlg, "xlt.langs");
            setFlags_Widget(langs, hidden_WidgetFlag, iTrue);
            iLabelWidget *acceptButton = acceptButton_Translation_(d);
            updateTextCStr_LabelWidget(acceptButton, "00:00");
            setFlags_Widget(as_Widget(acceptButton), disabled_WidgetFlag, iTrue);
            iTranslationProgressWidget *prog = new_TranslationProgressWidget();
            setPos_Widget(as_Widget(prog), langs->rect.pos);
            setSize_Widget(as_Widget(prog), langs->rect.size);
            addChild_Widget(d->dlg, iClob(prog));
            submit_Translation(d);
        }
        return iTrue;
    }
    if (equalWidget_Command(cmd, w, "translation.update")) {
        const uint32_t elapsed = SDL_GetTicks() - d->startTime;
        const unsigned seconds = (elapsed / 1000) % 60;
        const unsigned minutes = (elapsed / 60000);
        updateText_LabelWidget(acceptButton_Translation_(d),
                               collectNewFormat_String("%02u:%02u", minutes, seconds));
        return iTrue;
    }
    if (equalWidget_Command(cmd, w, "translation.finished")) {
        if (!isFinished_Translation(d)) {
            if (processResult_Translation_(d)) {
                destroy_Widget(d->dlg);
                d->dlg = NULL;
            }
        }
        return iTrue;
    }
    if (equalWidget_Command(cmd, d->dlg, "translation.cancel")) {
        if (status_TlsRequest(d->request) == submitted_TlsRequestStatus) {
            setFailed_Translation_(d, "Cancelled");
            updateTextCStr_LabelWidget(
                findMenuItem_Widget(findChild_Widget(d->dlg, "dialogbuttons"),
                                    "translation.cancel"),
                "Dismiss");
            cancel_TlsRequest(d->request);
        }
        else {
            destroy_Widget(d->dlg);
            d->dlg = NULL;
        }
        return iTrue;
    }
    return iFalse;
}

iBool isFinished_Translation(const iTranslation *d) {
    return d->dlg == NULL;
}