Package list fcitx-unikey / upstream/0.1.0 src / unikey-im.cpp
upstream/0.1.0

Tree @upstream/0.1.0 (Download .tar.gz)

unikey-im.cpp @upstream/0.1.0raw · history · blame

  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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
/***************************************************************************
 *   Copyright (C) 2012~2012 by CSSlayer                                   *
 *   wengxt@gmail.com                                                      *
 *                                                                         *
 *  This program is free software: you can redistribute it and/or modify   *
 *  it under the terms of the GNU General Public License as published by   *
 *  the Free Software Foundation, either version 3 of the License, or      *
 *  (at your option) any later version.                                    *
 *                                                                         *
 *  This program 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 General Public License for more details.                           *
 *                                                                         *
 *  You should have received a copy of the GNU General Public License      *
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.  *
 *                                                                         *
 ***************************************************************************/

#include <iconv.h>

#include <string>

#include <fcitx/fcitx.h>
#include <fcitx/ime.h>
#include <fcitx/hook.h>
#include <fcitx/instance.h>
#include <fcitx-config/xdg.h>
#include <fcitx-utils/log.h>
#include <errno.h>

#include "config.h"
#include "unikey.h"
#include "keycons.h"
#include "vnconv.h"
#include "unikey-config.h"
#include "unikey-im.h"
#include "unikey-ui.h"

#define CONVERT_BUF_SIZE 1024

#ifdef LIBICONV_SECOND_ARGUMENT_IS_CONST
typedef const char* IconvStr;
#else
typedef char* IconvStr;
#endif

static void* FcitxUnikeyCreate(FcitxInstance* instance);
static void FcitxUnikeyDestroy(void* arg);
static INPUT_RETURN_VALUE FcitxUnikeyDoInput(void* arg, FcitxKeySym sym, unsigned int state);
static boolean FcitxUnikeyInit(void* arg);
static void FcitxUnikeyReset(void* arg);
static void FcitxUnikeyResetUI(void* arg);
static INPUT_RETURN_VALUE FcitxUnikeyDoInputPreedit(FcitxUnikey* unikey, FcitxKeySym sym, unsigned int state);
static void FcitxUnikeyEraseChars(FcitxUnikey *unikey, int num_chars);
static void  FcitxUnikeyUpdatePreedit(FcitxUnikey *unikey);

static boolean LoadUnikeyConfig(UnikeyConfig* config);
static void ConfigUnikey(FcitxUnikey* unikey);
static void ReloadConfigFcitxUnikey(void* arg);
static void SaveUnikeyConfig(UnikeyConfig* fa);

static int latinToUtf(unsigned char* dst, unsigned char* src, int inSize, int* pOutSize);

FCITX_EXPORT_API
FcitxIMClass ime = {
    FcitxUnikeyCreate,
    FcitxUnikeyDestroy
};
FCITX_EXPORT_API
int ABI_VERSION = FCITX_ABI_VERSION;
static const unsigned int    Unikey_OC[]         = {CONV_CHARSET_XUTF8,
                                                    CONV_CHARSET_TCVN3,
                                                    CONV_CHARSET_VNIWIN,
                                                    CONV_CHARSET_VIQR,
                                                    CONV_CHARSET_BKHCM2,
                                                    CONV_CHARSET_UNI_CSTRING,
                                                    CONV_CHARSET_UNIREF,
                                                    CONV_CHARSET_UNIREF_HEX};
static const unsigned int    NUM_OUTPUTCHARSET   = sizeof(Unikey_OC)/sizeof(Unikey_OC[0]);

static const unsigned char WordBreakSyms[] =
{
    ',', ';', ':', '.', '\"', '\'', '!', '?', ' ',
    '<', '>', '=', '+', '-', '*', '/', '\\',
    '_', '~', '`', '@', '#', '$', '%', '^', '&', '(', ')', '{', '}', '[', ']',
    '|'
};

static const unsigned char WordAutoCommit[] =
{
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    'b', 'c', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n',
    'p', 'q', 'r', 's', 't', 'v', 'x', 'z',
    'B', 'C', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N',
    'P', 'Q', 'R', 'S', 'T', 'V', 'X', 'Z'
};



int FcitxUnikeyUcs4ToUtf8(FcitxUnikey* unikey, const unsigned int c, char buf[UTF8_MAX_LENGTH + 1])
{
    unsigned int str[2];
    str[0] = c;
    str[1] = 0;

    size_t ucslen = 1;
    size_t len = UTF8_MAX_LENGTH;
    len *= sizeof(char);
    ucslen *= sizeof(unsigned int);
    char* p = buf;
    IconvStr src = (IconvStr) str;
    iconv(unikey->conv, &src, &ucslen, &p, &len);
    return (UTF8_MAX_LENGTH - len) / sizeof(char);
}


void* FcitxUnikeyCreate(FcitxInstance* instance)
{
    FcitxUnikey* unikey = (FcitxUnikey*) fcitx_utils_malloc0(sizeof(FcitxUnikey));

    if (!LoadUnikeyConfig(&unikey->config))
    {
        free(unikey);
        return NULL;
    }
    unikey->owner = instance;
    unikey->preeditstr = new std::string;
    union {
        short s;
        unsigned char b[2];
    } endian;
    endian.s = 0x1234;
    if (endian.b[0] == 0x12)
        unikey->conv = iconv_open("utf-8", "ucs-4be");
    else
        unikey->conv = iconv_open("utf-8", "ucs-4le");

    FcitxIMIFace iface;
    memset(&iface, 0, sizeof(FcitxIMIFace));
    iface.Init = FcitxUnikeyInit;
    iface.ResetIM = FcitxUnikeyReset;
    iface.DoInput = FcitxUnikeyDoInput;
    iface.ReloadConfig = ReloadConfigFcitxUnikey;

    FcitxInstanceRegisterIMv2(
        instance,
        unikey,
        "unikey",
        _("Unikey"),
        "unikey",
        iface,
        1,
        "vi"
    );

    UnikeySetup();

    InitializeBar(unikey);
    InitializeMenu(unikey);

    ConfigUnikey(unikey);

    FcitxIMEventHook hk;
    hk.arg = unikey;
    hk.func = FcitxUnikeyResetUI;

    FcitxInstanceRegisterResetInputHook(instance, hk);

    return unikey;
}

void FcitxUnikeyDestroy(void* arg)
{
    UnikeyCleanup();
}


boolean FcitxUnikeyInit(void* arg)
{
    return true;
}

void FcitxUnikeyReset(void* arg)
{
    FcitxUnikey* unikey = (FcitxUnikey*) arg;

    UnikeyResetBuf();
    unikey->preeditstr->clear();
}

void FcitxUnikeyCommit(FcitxUnikey* unikey)
{
    if (unikey->preeditstr->length() > 0) {
        FcitxInstanceCommitString(unikey->owner, FcitxInstanceGetCurrentIC(unikey->owner), unikey->preeditstr->c_str());
    }
    FcitxUnikeyReset(unikey);
}

INPUT_RETURN_VALUE FcitxUnikeyDoInput(void* arg, FcitxKeySym sym, unsigned int state)
{
    FcitxUnikey* unikey = (FcitxUnikey*) arg;
    INPUT_RETURN_VALUE tmp;
    FcitxInputState* input = FcitxInstanceGetInputState(unikey->owner);
    /* use origin sym and state here */
    sym = (FcitxKeySym) FcitxInputStateGetKeySym(input);
    state = FcitxInputStateGetKeyState(input);

    tmp = FcitxUnikeyDoInputPreedit(unikey, sym, state);

    // check last keyevent with shift
    if (sym >= FcitxKey_space && sym <=FcitxKey_asciitilde)
    {
        unikey->last_key_with_shift = state & FcitxKeyState_Shift;
    }
    else
    {
        unikey->last_key_with_shift = false;
    } // end check last keyevent with shift

    return tmp;
}

INPUT_RETURN_VALUE FcitxUnikeyDoInputPreedit(FcitxUnikey* unikey, FcitxKeySym sym, unsigned int state)
{

    if (state & FcitxKeyState_Ctrl
             || state & FcitxKeyState_Alt // alternate mask
             || sym == FcitxKey_Control_L
             || sym == FcitxKey_Control_R
             || sym == FcitxKey_Tab
             || sym == FcitxKey_Return
             || sym == FcitxKey_Delete
             || sym == FcitxKey_KP_Enter
             || (sym >= FcitxKey_Home && sym <= FcitxKey_Insert)
             || (sym >= FcitxKey_KP_Home && sym <= FcitxKey_KP_Delete)
        )
    {
        FcitxUnikeyCommit(unikey);
        return IRV_FLAG_FORWARD_KEY;
    }

    else if ((sym >= FcitxKey_Caps_Lock && sym <= FcitxKey_Hyper_R)
            || (!(state & FcitxKeyState_Shift) && (sym == FcitxKey_Shift_L || sym == FcitxKey_Shift_R))  // when press one shift key
        )
    {
        return IRV_TO_PROCESS;
    }

    // capture BackSpace
    else if (sym == FcitxKey_BackSpace)
    {
        UnikeyBackspacePress();

        if (UnikeyBackspaces == 0 || unikey->preeditstr->empty())
        {
            FcitxUnikeyCommit(unikey);
            return IRV_FLAG_FORWARD_KEY;
        }
        else
        {
            if (unikey->preeditstr->length() <= (unsigned int)UnikeyBackspaces)
            {
                unikey->preeditstr->clear();
                unikey->auto_commit = true;
            }
            else
            {
                FcitxUnikeyEraseChars(unikey, UnikeyBackspaces);
                FcitxUnikeyUpdatePreedit(unikey);
            }

            // change tone position after press backspace
            if (UnikeyBufChars > 0)
            {
                if (unikey->config.oc == UKCONV_XUTF8)
                {
                    unikey->preeditstr->append((const char*)UnikeyBuf, UnikeyBufChars);
                }
                else
                {
                    static unsigned char buf[CONVERT_BUF_SIZE];
                    int bufSize = CONVERT_BUF_SIZE;

                    latinToUtf(buf, UnikeyBuf, UnikeyBufChars, &bufSize);
                    unikey->preeditstr->append((const char*)buf, CONVERT_BUF_SIZE - bufSize);
                }

                unikey->auto_commit = false;
                FcitxUnikeyUpdatePreedit(unikey);
            }
        }
        return IRV_DISPLAY_MESSAGE;
    } // end capture BackSpace

    else if (sym >=FcitxKey_KP_Multiply && sym <=FcitxKey_KP_9)
    {
        FcitxUnikeyCommit(unikey);
        return IRV_FLAG_FORWARD_KEY;
    }

    // capture ascii printable char
    else if ((sym >= FcitxKey_space && sym <=FcitxKey_asciitilde)
            || sym == FcitxKey_Shift_L || sym == FcitxKey_Shift_R) // sure this have FcitxKey_SHIFT_MASK
    {
        unsigned int i = 0;

        UnikeySetCapsState(state & FcitxKeyState_Shift, state & FcitxKeyState_CapsLock);

        // process sym

        // auto commit word that never need to change later in preedit string (like consonant - phu am)
        // if macro enabled, then not auto commit. Because macro may change any word
        if (unikey->ukopt.macroEnabled == 0 && (UnikeyAtWordBeginning() || unikey->auto_commit))
        {
            for (i =0; i < sizeof(WordAutoCommit); i++)
            {
                if (sym == WordAutoCommit[i])
                {
                    UnikeyPutChar(sym);
                    unikey->auto_commit = true;
                    return IRV_FLAG_FORWARD_KEY;
                }
            }
        } // end auto commit

        if ((unikey->config.im == UkTelex || unikey->config.im == UkSimpleTelex2)
            && unikey->config.process_w_at_begin == false
            && UnikeyAtWordBeginning()
            && (sym == FcitxKey_w || sym == FcitxKey_W))
        {
            UnikeyPutChar(sym);
            if (unikey->ukopt.macroEnabled == 0)
            {
                return IRV_TO_PROCESS;
            }
            else
            {
                unikey->preeditstr->append(sym==FcitxKey_w?"w":"W");
                FcitxUnikeyUpdatePreedit(unikey);
                return IRV_DISPLAY_MESSAGE;
            }
        }

        unikey->auto_commit = false;

        // shift + space, shift + shift event
        if ((unikey->last_key_with_shift == false && state & FcitxKeyState_Shift
                    && sym == FcitxKey_space && !UnikeyAtWordBeginning())
            || (sym == FcitxKey_Shift_L || sym == FcitxKey_Shift_R) // (&& state & FcitxKey_SHIFT_MASK), sure this have FcitxKey_SHIFT_MASK
           )
        {
            UnikeyRestoreKeyStrokes();
        } // end shift + space, shift + shift event

        else
        {
            UnikeyFilter(sym);
        }
        // end process sym

        // process result of ukengine
        if (UnikeyBackspaces > 0)
        {
            if (unikey->preeditstr->length() <= (unsigned int)UnikeyBackspaces)
            {
                unikey->preeditstr->clear();
            }
            else
            {
                FcitxUnikeyEraseChars(unikey, UnikeyBackspaces);
            }
        }

        if (UnikeyBufChars > 0)
        {
            if (unikey->config.oc == UKCONV_XUTF8)
            {
                unikey->preeditstr->append((const char*)UnikeyBuf, UnikeyBufChars);
            }
            else
            {
                unsigned char buf[CONVERT_BUF_SIZE + 1];
                int bufSize = CONVERT_BUF_SIZE;

                latinToUtf(buf, UnikeyBuf, UnikeyBufChars, &bufSize);
                unikey->preeditstr->append((const char*)buf, CONVERT_BUF_SIZE - bufSize);
            }
        }
        else if (sym != FcitxKey_Shift_L && sym != FcitxKey_Shift_R) // if ukengine not process
        {
            int n;
            char s[7] = {0, 0, 0, 0, 0, 0, 0};

            n = FcitxUnikeyUcs4ToUtf8(unikey, (unsigned int)sym, s); // convert ucs4 to utf8 char
            unikey->preeditstr->append(s, n);
        }
        // end process result of ukengine

        // commit string: if need
        if (unikey->preeditstr->length() > 0)
        {
            unsigned int i;
            for (i = 0; i < sizeof(WordBreakSyms); i++)
            {
                if (WordBreakSyms[i] == unikey->preeditstr->at(unikey->preeditstr->length()-1)
                    && WordBreakSyms[i] == sym)
                {
                    FcitxUnikeyCommit(unikey);
                    return IRV_DO_NOTHING;
                }
            }
        }
        // end commit string

        FcitxUnikeyUpdatePreedit(unikey);
        return IRV_DISPLAY_MESSAGE;
    } //end capture printable char

    // non process key

    FcitxUnikeyCommit(unikey);
    return IRV_FLAG_FORWARD_KEY;
}


// code from x-unikey, for convert charset that not is XUtf-8
int latinToUtf(unsigned char* dst, unsigned char* src, int inSize, int* pOutSize)
{
    int i;
    int outLeft;
    unsigned char ch;

    outLeft = *pOutSize;

    for (i=0; i<inSize; i++)
    {
        ch = *src++;
        if (ch < 0x80)
        {
            outLeft -= 1;
            if (outLeft >= 0)
                *dst++ = ch;
        }
        else
        {
            outLeft -= 2;
            if (outLeft >= 0)
            {
                *dst++ = (0xC0 | ch >> 6);
                *dst++ = (0x80 | (ch & 0x3F));
            }
        }
    }

    *pOutSize = outLeft;
    return (outLeft >= 0);
}


static void FcitxUnikeyEraseChars(FcitxUnikey *unikey, int num_chars)
{
    int i, k;
    unsigned char c;
    k = num_chars;

    for ( i = unikey->preeditstr->length()-1; i >= 0 && k > 0; i--)
    {
        c = unikey->preeditstr->at(i);

        // count down if byte is begin byte of utf-8 char
        if (c < (unsigned char)'\x80' || c >= (unsigned char)'\xC0')
        {
            k--;
        }
    }

    unikey->preeditstr->erase(i+1);
}


static void  FcitxUnikeyUpdatePreedit(FcitxUnikey *unikey)
{
    FcitxInputState* input = FcitxInstanceGetInputState(unikey->owner);
    FcitxMessages* preedit = FcitxInputStateGetPreedit(input);
    FcitxMessages* clientPreedit = FcitxInputStateGetClientPreedit(input);
    FcitxInputContext* ic = FcitxInstanceGetCurrentIC(unikey->owner);
    FcitxProfile* profile = FcitxInstanceGetProfile(unikey->owner);
    FcitxInstanceCleanInputWindowUp(unikey->owner);
    if (ic && ((ic->contextCaps & CAPACITY_PREEDIT) == 0 || !profile->bUsePreedit)) {
        FcitxMessagesAddMessageAtLast(preedit, MSG_INPUT, "%s", unikey->preeditstr->c_str());
        FcitxInputStateSetCursorPos(input, unikey->preeditstr->size());
    }
    FcitxMessagesAddMessageAtLast(clientPreedit, MSG_INPUT, "%s", unikey->preeditstr->c_str());
    FcitxInputStateSetClientCursorPos(input, unikey->preeditstr->size());
}

CONFIG_DESC_DEFINE(GetUnikeyConfigDesc, "fcitx-unikey.desc")

boolean LoadUnikeyConfig(UnikeyConfig* config)
{
    FcitxConfigFileDesc *configDesc = GetUnikeyConfigDesc();
    if (!configDesc)
        return false;

    FILE *fp = FcitxXDGGetFileUserWithPrefix("conf", "fcitx-unikey.config", "r", NULL);

    if (!fp)
    {
        if (errno == ENOENT)
            SaveUnikeyConfig(config);
    }
    FcitxConfigFile *cfile = FcitxConfigParseConfigFileFp(fp, configDesc);

    UnikeyConfigConfigBind(config, cfile, configDesc);
    FcitxConfigBindSync(&config->gconfig);

    if (fp)
        fclose(fp);
    return true;
}

void ConfigUnikey(FcitxUnikey* unikey)
{
    unikey->ukopt.macroEnabled          = unikey->config.macro;
    unikey->ukopt.spellCheckEnabled     = unikey->config.spellCheck;
    unikey->ukopt.autoNonVnRestore      = unikey->config.autoNonVnRestore;
    unikey->ukopt.modernStyle           = unikey->config.modernStyle;
    unikey->ukopt.freeMarking           = unikey->config.freeMarking;
    UnikeySetInputMethod(unikey->config.im);
    UnikeySetOutputCharset(Unikey_OC[unikey->config.oc]);
    UnikeySetOptions(&unikey->ukopt);

    UpdateUnikeyUI(unikey);
}

void ReloadConfigFcitxUnikey(void* arg)
{
    FcitxUnikey* unikey = (FcitxUnikey*) arg;
    LoadUnikeyConfig(&unikey->config);
    ConfigUnikey(unikey);
}

void SaveUnikeyConfig(UnikeyConfig* fa)
{
    FcitxConfigFileDesc *configDesc = GetUnikeyConfigDesc();
    FILE *fp = FcitxXDGGetFileUserWithPrefix("conf", "fcitx-unikey.config", "w", NULL);
    FcitxConfigSaveConfigFileFp(fp, &fa->gconfig, configDesc);
    if (fp)
        fclose(fp);
}

void FcitxUnikeyResetUI(void* arg)
{
    FcitxUnikey* unikey = (FcitxUnikey*) arg;
    FcitxInstance* instance = unikey->owner;
    FcitxIM* im = FcitxInstanceGetCurrentIM(instance);
    boolean visible;
    if (!im || strcmp(im->uniqueName, "unikey") != 0)
        visible = false;
    else
        visible = true;
    FcitxUISetStatusVisable(instance, "unikey-input-method", visible);
    FcitxUISetStatusVisable(instance, "unikey-output-charset", visible);
    FcitxUISetStatusVisable(instance, "unikey-spell-check", visible);
    FcitxUISetStatusVisable(instance, "unikey-macro", visible);
}

void UpdateUnikeyConfig(FcitxUnikey* unikey)
{
    ConfigUnikey(unikey);
    SaveUnikeyConfig(&unikey->config);
}