skk.c 25.6 KB
Newer Older
Yichao Yu's avatar
Yichao Yu committed
1 2 3
/***************************************************************************
 *   Copyright (C) 2012~2012 by Yichao Yu                                  *
 *   yyc1992@gmail.com                                                     *
Weng Xuetian's avatar
Weng Xuetian committed
4 5
 *   Copyright (C) 2012~2013 by Weng Xuetian                               *
 *   wengxt@gmail.com                                                      *
Yichao Yu's avatar
Yichao Yu committed
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
 *                                                                         *
 *   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 2 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, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.              *
 ***************************************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcitx/ime.h>
#include <fcitx-config/fcitx-config.h>
#include <fcitx-config/xdg.h>
#include <fcitx-config/hotkey.h>
#include <fcitx-utils/log.h>
#include <fcitx/candidate.h>
#include <fcitx/context.h>
#include <fcitx/keys.h>
#include <fcitx/ui.h>
Weng Xuetian's avatar
Weng Xuetian committed
35
#include <fcitx/hook.h>
36
#include <libskk/libskk.h>
Yichao Yu's avatar
Yichao Yu committed
37 38 39 40

#include "skk.h"
#include "config.h"

Weng Xuetian's avatar
Weng Xuetian committed
41 42
UT_icd dict_icd = { sizeof(void*), 0, 0, 0};

Yichao Yu's avatar
Yichao Yu committed
43 44
static void *FcitxSkkCreate(FcitxInstance *instance);
static void FcitxSkkDestroy(void *arg);
Weng Xuetian's avatar
Weng Xuetian committed
45 46 47 48 49 50 51
static void FcitxSkkReloadConfig(void *arg);
static boolean FcitxSkkLoadDictionary(FcitxSkk* skk);
static boolean FcitxSkkLoadRule(FcitxSkk* skk);
static void FcitxSkkApplyConfig(FcitxSkk* skk);

CONFIG_DEFINE_LOAD_AND_SAVE(Skk, FcitxSkkConfig, "fcitx-skk")

Yichao Yu's avatar
Yichao Yu committed
52
static boolean FcitxSkkInit(void *arg);
53 54
static INPUT_RETURN_VALUE FcitxSkkDoInputReal(void *arg, FcitxKeySym sym,
                                          unsigned int state);
Yichao Yu's avatar
Yichao Yu committed
55 56
static INPUT_RETURN_VALUE FcitxSkkDoInput(void *arg, FcitxKeySym sym,
                                          unsigned int state);
57 58 59 60
static INPUT_RETURN_VALUE FcitxSkkDoReleaseInput(void *arg, FcitxKeySym sym,
                                          unsigned int state);
static INPUT_RETURN_VALUE FcitxSkkDoCandidate(void *arg, FcitxKeySym sym,
                                             unsigned int state);
Yichao Yu's avatar
Yichao Yu committed
61 62 63
static INPUT_RETURN_VALUE FcitxSkkGetCandWords(void *arg);
static void FcitxSkkReset(void *arg);

Weng Xuetian's avatar
Weng Xuetian committed
64 65 66 67 68 69 70 71 72
FCITX_DEFINE_PLUGIN(fcitx_skk, ime2, FcitxIMClass2) = {
    FcitxSkkCreate,
    FcitxSkkDestroy,
    FcitxSkkReloadConfig,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL
Yichao Yu's avatar
Yichao Yu committed
73 74 75 76 77 78 79 80 81 82
};

static const FcitxIMIFace skk_iface = {
    .Init = FcitxSkkInit,
    .ResetIM = FcitxSkkReset,
    .DoInput = FcitxSkkDoInput,
    .GetCandWords = FcitxSkkGetCandWords,
    .PhraseTips = NULL,
    .Save = NULL,
    .ReloadConfig = NULL,
Weng Xuetian's avatar
Weng Xuetian committed
83
    .KeyBlocker = 0,
Yichao Yu's avatar
Yichao Yu committed
84
    .UpdateSurroundingText = NULL,
85
    .DoReleaseInput = FcitxSkkDoReleaseInput,
Yichao Yu's avatar
Yichao Yu committed
86 87
};

Weng Xuetian's avatar
Weng Xuetian committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101
typedef struct _SkkStatus {
    const char* icon;
    const char* label;
    const char* description;
} SkkStatus;

SkkStatus input_mode_status[] = {
    {"",  "\xe3\x81\x82", N_("Hiragana") },
    {"", "\xe3\x82\xa2", N_("Katakana") },
    {"", "\xef\xbd\xb1", N_("Half width Katakana") },
    {"", "A", N_("Latin") },
    {"", "\xef\xbc\xa1", N_("Wide latin") },
};

Yichao Yu's avatar
Yichao Yu committed
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
static void
ut_gobject_cpy(void *dst, const void *src)
{
    GObject *const *_src = (GObject *const*)src;
    GObject **_dst = (GObject**)dst;
    *_dst = g_object_ref(*_src);
}

static void
ut_gobject_dtor(void *self)
{
    GObject **_self = (GObject**)self;
    g_object_unref(*_self);
}

static const UT_icd gobject_icd = {
    .sz = sizeof(GObject*),
    .dtor = ut_gobject_dtor,
    .copy = ut_gobject_cpy,
};

Weng Xuetian's avatar
Weng Xuetian committed
123
void skk_candidate_update_preedit_cb (SkkContext* context, GParamSpec *pspec,  gpointer user_data)
124 125 126 127 128 129 130 131 132
{
    FcitxSkk *skk = (FcitxSkk*) user_data;
    skk->updatePreedit = true;
}

void skk_candidate_list_selected_cb (SkkCandidateList* self, SkkCandidate* c, gpointer user_data)
{
    FcitxSkk *skk = (FcitxSkk*) user_data;
    skk->selected = true;
Weng Xuetian's avatar
Weng Xuetian committed
133
    gchar* output = skk_context_poll_output(skk->context);
134 135 136 137 138 139 140 141

    if (output && strlen(output) > 0) {
        FcitxInstanceCommitString(skk->owner, FcitxInstanceGetCurrentIC(skk->owner), output);
    }

    g_free(output);
}

Weng Xuetian's avatar
Weng Xuetian committed
142 143 144 145 146 147
void skk_candidate_list_popuplated_cb (SkkCandidateList* self, gpointer user_data)
{
    FcitxSkk *skk = (FcitxSkk*) user_data;
    skk->update_candidate = true;
}

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
static gboolean skk_context_retrieve_surrounding_text_cb (SkkContext* self, gchar** text, guint* cursor_pos, gpointer user_data) {
    FcitxSkk *skk = (FcitxSkk*) user_data;
    FcitxInputContext* ic = FcitxInstanceGetCurrentIC(skk->owner);
    if (!ic || !(ic->contextCaps & CAPACITY_SURROUNDING_TEXT))
        return false;

    char* _text = NULL;
    unsigned int _cursor_pos;
    if (!FcitxInstanceGetSurroundingText(skk->owner, ic, &_text, &_cursor_pos, NULL))
        return false;

    *text = g_strdup(_text);
    *cursor_pos = _cursor_pos;

    fcitx_utils_free(_text);

    return true;
}

static gboolean skk_context_delete_surrounding_text_cb (SkkContext* self, gint offset, guint nchars, gpointer user_data) {
    FcitxSkk *skk = (FcitxSkk*) user_data;
    FcitxInputContext* ic = FcitxInstanceGetCurrentIC(skk->owner);
    if (!ic || !(ic->contextCaps & CAPACITY_SURROUNDING_TEXT))
        return false;
    FcitxInstanceDeleteSurroundingText(skk->owner, ic, offset, nchars);
    return true;
}

Weng Xuetian's avatar
Weng Xuetian committed
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
typedef enum _FcitxSkkDictType {
    FSDT_Invalid,
    FSDT_File,
    FSTD_Server
} FcitxSkkDictType;


void FcitxSkkResetHook(void *arg)
{
    FcitxSkk *skk = (FcitxSkk*)arg;
    FcitxIM* im = FcitxInstanceGetCurrentIM(skk->owner);
#define RESET_STATUS(STATUS_NAME) \
    if (im && strcmp(im->uniqueName, "skk") == 0) \
        FcitxUISetStatusVisable(skk->owner, STATUS_NAME, true); \
    else \
        FcitxUISetStatusVisable(skk->owner, STATUS_NAME, false);

    RESET_STATUS("skk-input-mode")
}

boolean FcitxSkkLoadDictionary(FcitxSkk* skk)
{
    FILE* fp = FcitxXDGGetFileWithPrefix("skk", "dictionary_list", "r", NULL);
    if (!fp) {
        return false;
    }

    UT_array dictionaries;
    utarray_init(&dictionaries, &dict_icd);

    char *buf = NULL;
    size_t len = 0;
    char *trimmed = NULL;

    while (getline(&buf, &len, fp) != -1) {
        if (trimmed)
            free(trimmed);
        trimmed = fcitx_utils_trim(buf);

        UT_array* list = fcitx_utils_split_string(trimmed, ',');
        do {
            if (utarray_len(list) < 3) {
                break;
            }

            FcitxSkkDictType type = FSDT_Invalid;
            int mode = 0;
            char* path = NULL;
            char* host = NULL;
            char* port = NULL;
            char* encoding = NULL;
            utarray_foreach(item, list, char*) {
                char* key = *item;
                char* value = strchr(*item, '=');
                if (!value)
                    continue;
                *value = '\0';
                value++;

                if (strcmp(key, "type") == 0) {
                    if (strcmp(value, "file") == 0) {
                        type = FSDT_File;
                    } else if (strcmp(value, "server") == 0) {
                        type = FSTD_Server;
                    }
                } else if (strcmp(key, "file") == 0) {
                    path = value;
                } else if (strcmp(key, "mode") == 0) {
                    if (strcmp(value, "readonly") == 0) {
                        mode = 1;
                    } else if (strcmp(value, "readwrite") == 0) {
                        mode = 2;
                    }
                } else if (strcmp(key, "host") == 0) {
                    host = value;
                } else if (strcmp(key, "port") == 0) {
                    port = value;
                } else if (strcmp(key, "encoding") == 0) {
                    encoding = value;
                }
            }

            encoding = encoding ? encoding : "EUC-JP";

            if (type == FSDT_Invalid) {
                break;
            } else if (type == FSDT_File) {
                if (path == NULL || mode == 0) {
                    break;
                }
                if (mode == 1) {
                    if(strlen(path) > 4 && !strcmp(path + strlen(path) - 4, ".cdb")) {
                        SkkCdbDict* dict = skk_cdb_dict_new(path, encoding, NULL);
                        if (dict) {
                            utarray_push_back(&dictionaries, &dict);
                        }
                    } else {
                        SkkFileDict* dict = skk_file_dict_new(path, encoding, NULL);
                        if (dict) {
                            utarray_push_back(&dictionaries, &dict);
                        }
                    }
                } else {
                    char* needfree = NULL;
                    char* realpath = NULL;
                    if (strncmp(path, "$FCITX_CONFIG_DIR/", strlen("$FCITX_CONFIG_DIR/")) == 0) {
                        FcitxXDGGetFileUserWithPrefix("", path + strlen("$FCITX_CONFIG_DIR/"), NULL, &needfree);
                        realpath = needfree;
                    } else {
                        realpath = path;
                    }
                    SkkUserDict* userdict = skk_user_dict_new(realpath, encoding, NULL);
                    if (needfree) {
                        free(needfree);
                    }
                    if (userdict) {
                        utarray_push_back(&dictionaries, &userdict);
                    }
                }
            } else if (type == FSTD_Server) {
                host = host ? host : "localhost";
                port = port ? port : "1178";

                errno = 0;
                int iPort = atoi(port);
                if (iPort <= 0 || iPort > UINT16_MAX) {
                    break;
                }

                SkkSkkServ* dict = skk_skk_serv_new(host, iPort, encoding, NULL);
                if (dict) {
                    utarray_push_back(&dictionaries, &dict);
                }
            }

        } while(0);
        fcitx_utils_free_string_list(list);
    }

    if (buf)
        free(buf);
    if (trimmed)
        free(trimmed);

    boolean result = false;
    if (utarray_len(&dictionaries) != 0) {
        result = true;
        skk_context_set_dictionaries(skk->context,
                                     (SkkDict**)utarray_front(&dictionaries),
                                     utarray_len(&dictionaries));
    }

    utarray_done(&dictionaries);
    return result;
}

boolean FcitxSkkLoadRule(FcitxSkk* skk)
{
    FILE* fp = FcitxXDGGetFileWithPrefix("skk", "rule", "r", NULL);
    SkkRuleMetadata* meta = NULL;

    do {
        if (!fp) {
            break;
        }

        char* line = NULL;
        size_t bufsize = 0;
        getline(&line, &bufsize, fp);
        fclose(fp);

        if (!line) {
            break;
        }

        char* trimmed = fcitx_utils_trim(line);
        meta = skk_rule_find_rule(trimmed);
        free(trimmed);
        free(line);
    } while(0);

    if (!meta) {
        meta = skk_rule_find_rule("default");
        if (!meta) {
            return false;
        }
    }

    SkkRule* rule = skk_rule_new(meta->name, NULL);
    if (!rule) {
        return false;
    }

    skk_context_set_typing_rule(skk->context, rule);
    return true;
}


const char* FcitxSkkGetInputModeIconName(void* arg)
{
    FcitxSkk *skk = (FcitxSkk*)arg;
    return input_mode_status[skk_context_get_input_mode(skk->context)].icon;
}

void FcitxSkkUpdateInputModeMenu(struct _FcitxUIMenu *menu)
{
    FcitxSkk *skk = (FcitxSkk*) menu->priv;
    menu->mark = skk_context_get_input_mode(skk->context);
}

boolean FcitxSkkInputModeMenuAction(struct _FcitxUIMenu *menu, int index)
{
    FcitxSkk *skk = (FcitxSkk*) menu->priv;
    skk_context_set_input_mode(skk->context, (SkkInputMode) index);
    return true;
}

void FcitxSkkUpdateInputMode(FcitxSkk* skk)
{
    SkkInputMode mode = skk_context_get_input_mode(skk->context);
    FcitxUISetStatusString(skk->owner,
                           "skk-input-mode",
                           _(input_mode_status[mode].label),
                           _(input_mode_status[mode].description));
}

static void  _skk_input_mode_changed_cb                (GObject    *gobject,
                                                        GParamSpec *pspec,
                                                        gpointer    user_data)
{
    FcitxSkk *skk = (FcitxSkk*) user_data;
    FcitxSkkUpdateInputMode(skk);
}

Yichao Yu's avatar
Yichao Yu committed
410 411 412 413 414
static void*
FcitxSkkCreate(FcitxInstance *instance)
{
    FcitxSkk *skk = fcitx_utils_new(FcitxSkk);
    bindtextdomain("fcitx-skk", LOCALEDIR);
415
    bind_textdomain_codeset("fcitx-skk", "UTF-8");
Weng Xuetian's avatar
Weng Xuetian committed
416
    skk->owner = instance;
Yichao Yu's avatar
Yichao Yu committed
417

Weng Xuetian's avatar
Weng Xuetian committed
418 419 420 421 422 423
    if (!SkkLoadConfig(&skk->config)) {
        free(skk);
        return NULL;
    }

#if !GLIB_CHECK_VERSION(2, 36, 0)
424
    g_type_init();
Weng Xuetian's avatar
Weng Xuetian committed
425
#endif
426

Yichao Yu's avatar
Yichao Yu committed
427 428
    skk_init();

Weng Xuetian's avatar
Weng Xuetian committed
429
    skk->context = skk_context_new(0, 0);
Yichao Yu's avatar
Yichao Yu committed
430

Weng Xuetian's avatar
Weng Xuetian committed
431 432 433 434 435 436
    if (!FcitxSkkLoadDictionary(skk) || !FcitxSkkLoadRule(skk)) {
        free(skk);
        return NULL;
    }
    skk_context_set_period_style(skk->context, SKK_PERIOD_STYLE_JA_JA);
    skk_context_set_input_mode(skk->context, SKK_INPUT_MODE_HIRAGANA);
437

Weng Xuetian's avatar
Weng Xuetian committed
438
    FcitxSkkApplyConfig(skk);
439

Weng Xuetian's avatar
Weng Xuetian committed
440 441
    FcitxInstanceRegisterIMv2(instance, skk, "skk", _("Skk"), "skk",
                              skk_iface, 1, "ja");
442

Weng Xuetian's avatar
Weng Xuetian committed
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
#define INIT_MENU(VARNAME, NAME, I18NNAME, STATUS_NAME, STATUS_ARRAY, SIZE) \
    do { \
        FcitxUIRegisterComplexStatus(instance, skk, \
            STATUS_NAME, \
            I18NNAME, \
            I18NNAME, \
            NULL, \
            FcitxSkkGet##NAME##IconName \
        ); \
        FcitxMenuInit(&VARNAME); \
        VARNAME.name = strdup(I18NNAME); \
        VARNAME.candStatusBind = strdup(STATUS_NAME); \
        VARNAME.UpdateMenu = FcitxSkkUpdate##NAME##Menu; \
        VARNAME.MenuAction = FcitxSkk##NAME##MenuAction; \
        VARNAME.priv = skk; \
        VARNAME.isSubMenu = false; \
        int i; \
        for (i = 0; i < SIZE; i ++) \
            FcitxMenuAddMenuItem(&VARNAME, _(STATUS_ARRAY[i].label), MENUTYPE_SIMPLE, NULL); \
        FcitxUIRegisterMenu(instance, &VARNAME); \
        FcitxUISetStatusVisable(instance, STATUS_NAME, false); \
    } while(0)

    INIT_MENU(skk->inputModeMenu, InputMode, _("Input Mode"), "skk-input-mode", input_mode_status, SKK_INPUT_MODE_LAST);

    skk->handler = g_signal_connect(skk->context, "notify::input-mode", G_CALLBACK(_skk_input_mode_changed_cb), skk);
    FcitxSkkUpdateInputMode(skk);
    skk->candidate_selected_handler = g_signal_connect(skk_context_get_candidates(skk->context), "selected", G_CALLBACK(skk_candidate_list_selected_cb), skk);
    skk->candidate_populated_handler = g_signal_connect(skk_context_get_candidates(skk->context), "populated", G_CALLBACK(skk_candidate_list_popuplated_cb), skk);
    skk->notify_preedit_handler = g_signal_connect(skk->context, "notify::preedit", G_CALLBACK(skk_candidate_update_preedit_cb), skk);
    skk->retrieve_surrounding_text_handler = g_signal_connect(skk->context, "retrieve_surrounding_text", G_CALLBACK(skk_context_retrieve_surrounding_text_cb), skk);
    skk->delete_surrounding_text_handler = g_signal_connect(skk->context, "delete_surrounding_text", G_CALLBACK(skk_context_delete_surrounding_text_cb), skk);


    gchar* AUTO_START_HENKAN_KEYWORDS[] = {
478 479 480 481 482
        "を", "、", "。", ".", ",", "?", "」",
        "!", ";", ":", ")", ";", ":", ")",
        "”", "】", "』", "》", "〉", "}", "]",
        "〕", "}", "]", "?", ".", ",", "!"
    };
Weng Xuetian's avatar
Weng Xuetian committed
483
    skk_context_set_auto_start_henkan_keywords(skk->context, AUTO_START_HENKAN_KEYWORDS, G_N_ELEMENTS(AUTO_START_HENKAN_KEYWORDS));
484

Weng Xuetian's avatar
Weng Xuetian committed
485 486 487 488 489
    FcitxIMEventHook hk;
    hk.arg = skk;
    hk.func = FcitxSkkResetHook;
    FcitxInstanceRegisterResetInputHook(instance, hk);

Yichao Yu's avatar
Yichao Yu committed
490 491 492
    return skk;
}

493 494


Yichao Yu's avatar
Yichao Yu committed
495 496 497 498 499 500
static void
FcitxSkkDestroy(void *arg)
{
    FcitxSkk *skk = (FcitxSkk*)arg;
    if (fcitx_unlikely(!arg))
        return;
Weng Xuetian's avatar
Weng Xuetian committed
501 502 503 504 505 506 507
    g_signal_handler_disconnect(skk_context_get_candidates(skk->context), skk->candidate_selected_handler);
    g_signal_handler_disconnect(skk_context_get_candidates(skk->context), skk->candidate_populated_handler);
    g_signal_handler_disconnect(skk->context, skk->handler);
    g_signal_handler_disconnect(skk->context, skk->notify_preedit_handler);
    g_signal_handler_disconnect(skk->context, skk->retrieve_surrounding_text_handler);
    g_signal_handler_disconnect(skk->context, skk->delete_surrounding_text_handler);
    g_object_unref(skk->context);
Yichao Yu's avatar
Yichao Yu committed
508 509 510 511 512 513 514 515 516
    free(arg);
}

static boolean
FcitxSkkInit(void *arg)
{
    FcitxSkk *skk = (FcitxSkk*)arg;
    if (!arg)
        return false;
Yichao Yu's avatar
Yichao Yu committed
517
    FcitxInstanceSetContext(skk->owner, CONTEXT_IM_KEYBOARD_LAYOUT, "ja");
Weng Xuetian's avatar
Weng Xuetian committed
518 519 520 521 522 523
    boolean flag = true;
    FcitxInstanceSetContext(skk->owner, CONTEXT_IM_KEYBOARD_LAYOUT, "jp");
    FcitxInstanceSetContext(skk->owner, CONTEXT_DISABLE_AUTOENG, &flag);
    FcitxInstanceSetContext(skk->owner, CONTEXT_DISABLE_QUICKPHRASE, &flag);
    FcitxInstanceSetContext(skk->owner, CONTEXT_DISABLE_FULLWIDTH, &flag);
    FcitxInstanceSetContext(skk->owner, CONTEXT_DISABLE_AUTO_FIRST_CANDIDATE_HIGHTLIGHT, &flag);
Yichao Yu's avatar
Yichao Yu committed
524 525 526 527 528 529 530
    return true;
}

static INPUT_RETURN_VALUE
FcitxSkkDoInput(void *arg, FcitxKeySym sym, unsigned int state)
{
    FcitxSkk *skk = (FcitxSkk*)arg;
531 532 533 534 535 536 537 538 539 540 541 542 543 544
    FcitxInputState* input = FcitxInstanceGetInputState(skk->owner);
    sym = FcitxInputStateGetKeySym(input);
    state = FcitxInputStateGetKeyState(input);

    return FcitxSkkDoInputReal(skk, sym, state);
}

static INPUT_RETURN_VALUE
FcitxSkkDoInputReal(void *arg, FcitxKeySym sym, unsigned int state)
{
    FcitxSkk *skk = (FcitxSkk*)arg;
    // Filter out unnecessary modifier bits
    // FIXME: should resolve virtual modifiers

Weng Xuetian's avatar
Weng Xuetian committed
545
    if (skk_candidate_list_get_page_visible(skk_context_get_candidates(skk->context))) {
Weng Xuetian's avatar
Weng Xuetian committed
546 547 548
        INPUT_RETURN_VALUE result = FcitxSkkDoCandidate (skk, sym, state);
        if (result == IRV_TO_PROCESS)
            return result;
549 550 551
    }

    SkkModifierType modifiers = (SkkModifierType) state & (FcitxKeyState_SimpleMask | (1 << 30));
Weng Xuetian's avatar
Weng Xuetian committed
552
    SkkKeyEvent* key = skk_key_event_new_from_x_keysym(sym, modifiers, NULL);
553 554 555
    if (!key)
        return IRV_TO_PROCESS;

Weng Xuetian's avatar
Weng Xuetian committed
556 557
    gboolean retval = skk_context_process_key_event(skk->context, key);
    gchar* output = skk_context_poll_output(skk->context);
558 559 560 561 562 563 564 565

    g_object_unref(key);

    if (output && strlen(output) > 0) {
        FcitxInstanceCommitString(skk->owner, FcitxInstanceGetCurrentIC(skk->owner), output);
    }

    g_free(output);
Weng Xuetian's avatar
Weng Xuetian committed
566
    return retval ? (skk->updatePreedit || skk->update_candidate ?  IRV_DISPLAY_CANDWORDS : IRV_DO_NOTHING) : IRV_TO_PROCESS;
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
}

static INPUT_RETURN_VALUE
FcitxSkkDoReleaseInput(void *arg, FcitxKeySym sym, unsigned int state)
{
    FcitxSkk *skk = (FcitxSkk*)arg;
    FcitxInputState* input = FcitxInstanceGetInputState(skk->owner);
    sym = FcitxInputStateGetKeySym(input);
    state = FcitxInputStateGetKeyState(input);

    return FcitxSkkDoInputReal(skk, sym, state | (1 << 30));
}

INPUT_RETURN_VALUE FcitxSkkDoCandidate(void* arg, FcitxKeySym sym, unsigned int state)
{
    FcitxSkk *skk = (FcitxSkk*)arg;
    FcitxInputState* input = FcitxInstanceGetInputState(skk->owner);
Weng Xuetian's avatar
Weng Xuetian committed
584
    FcitxGlobalConfig *fc = FcitxInstanceGetGlobalConfig(skk->owner);
585 586
    FcitxCandidateWordList* candList = FcitxInputStateGetCandidateList(input);

Weng Xuetian's avatar
Weng Xuetian committed
587 588 589 590 591 592 593 594 595 596
    if (FcitxHotkeyIsHotKey(sym, state,
                            FcitxConfigPrevPageKey(skk->owner, fc))) {
        return IRV_TO_PROCESS;
    } else if (FcitxHotkeyIsHotKey(sym, state,
                                    FcitxConfigNextPageKey(skk->owner, fc))) {
        return IRV_TO_PROCESS;
    } else if (FcitxCandidateWordCheckChooseKey(candList, sym, state) >= 0) {
        return IRV_TO_PROCESS;
    }
    return IRV_DO_NOTHING;
597 598 599 600 601 602
}

static INPUT_RETURN_VALUE
FcitxSkkGetCandWord(void* arg, FcitxCandidateWord* cand)
{
    FcitxSkk *skk = (FcitxSkk*)arg;
Weng Xuetian's avatar
Weng Xuetian committed
603
    SkkCandidateList* skkCandList = skk_context_get_candidates(skk->context);
604
    int idx = *(int*) cand->priv;
Weng Xuetian's avatar
Weng Xuetian committed
605 606 607 608
    gboolean retval = skk_candidate_list_select_at(skkCandList, idx % skk_candidate_list_get_page_size(skkCandList));
    if (retval) {
        return IRV_DISPLAY_CANDWORDS;
    }
609

Weng Xuetian's avatar
Weng Xuetian committed
610
    return IRV_TO_PROCESS;
611 612 613 614
}

boolean FcitxSkkPaging(void* arg, boolean prev) {
    FcitxSkk *skk = (FcitxSkk*)arg;
Weng Xuetian's avatar
Weng Xuetian committed
615
    SkkCandidateList* skkCandList = skk_context_get_candidates(skk->context);
616 617
    boolean result;
    if (prev)
Weng Xuetian's avatar
Weng Xuetian committed
618
        result = skk_candidate_list_page_up(skkCandList);
619
    else
Weng Xuetian's avatar
Weng Xuetian committed
620
        result = skk_candidate_list_page_down(skkCandList);
621
    FcitxSkkGetCandWords(skk);
Weng Xuetian's avatar
Weng Xuetian committed
622
    return result;
Yichao Yu's avatar
Yichao Yu committed
623 624 625 626 627 628
}

static INPUT_RETURN_VALUE
FcitxSkkGetCandWords(void *arg)
{
    FcitxSkk *skk = (FcitxSkk*)arg;
629 630 631
    FcitxInstanceCleanInputWindow(skk->owner);
    FcitxInputState* input = FcitxInstanceGetInputState(skk->owner);
    FcitxCandidateWordList* candList = FcitxInputStateGetCandidateList(input);
Weng Xuetian's avatar
Weng Xuetian committed
632
    SkkCandidateList* skkCandList = skk_context_get_candidates(skk->context);
633 634 635 636 637 638 639 640 641 642 643 644 645 646
    switch (skk->config.candidateChooseKey){
    case ChooseABCD:
        FcitxCandidateWordSetChoose(candList, ABCD_STR_CHOOSE);
        break;
    case ChooseASDF:
        FcitxCandidateWordSetChoose(candList, ASDF_STR_CHOOSE);
        break;
    case ChooseDigit:
// FALL THRU
    default:
        FcitxCandidateWordSetChoose(candList, DIGIT_STR_CHOOSE);
        break;
    }

Weng Xuetian's avatar
Weng Xuetian committed
647 648
    FcitxCandidateWordSetPageSize(candList, skk->config.pageSize);
    FcitxCandidateWordSetLayoutHint(candList, skk->config.candidateLayout);
649 650 651 652

    if (skk_candidate_list_get_page_visible(skkCandList)) {
        int i = 0;
        int j = 0;
Weng Xuetian's avatar
Weng Xuetian committed
653 654 655 656 657
        guint size = skk_candidate_list_get_size(skkCandList);
        gint cursor_pos = skk_candidate_list_get_cursor_pos(skkCandList);
        guint page_start = skk_candidate_list_get_page_start(skkCandList);
        guint page_size = skk_candidate_list_get_page_size(skkCandList);
        for (i = skk_candidate_list_get_page_start(skkCandList), j = 0; i < size; i ++, j++) {
Weng Xuetian's avatar
Weng Xuetian committed
658
            SkkCandidate* skkCandidate = skk_candidate_list_get(skkCandList, i);
659 660 661 662 663 664 665 666
            FcitxCandidateWord word;
            word.callback = FcitxSkkGetCandWord;
            word.extraType = MSG_OTHER;
            word.owner = skk;
            int* id = fcitx_utils_new(int);
            *id = j;
            word.priv = id;
            word.strExtra = NULL;
Weng Xuetian's avatar
Weng Xuetian committed
667 668 669 670
            if (skk->config.showAnnotation && skk_candidate_get_annotation(skkCandidate)) {
                fcitx_utils_alloc_cat_str(word.strExtra, " [", skk_candidate_get_annotation(skkCandidate), "]");
            }
            word.strWord = strdup(skk_candidate_get_text(skkCandidate));
Weng Xuetian's avatar
Weng Xuetian committed
671
            if (i == cursor_pos) {
672 673 674 675 676 677
                word.wordType = MSG_CANDIATE_CURSOR;
            } else {
                word.wordType = MSG_OTHER;
            }
            FcitxCandidateWordAppend(candList, &word);
        }
Weng Xuetian's avatar
Weng Xuetian committed
678 679
        FcitxCandidateWordSetFocus(candList, cursor_pos - page_start);
        FcitxCandidateWordSetOverridePaging(candList, (cursor_pos - page_start) >= page_size, (size - cursor_pos) >= page_size, FcitxSkkPaging, skk, NULL);
680
    }
Weng Xuetian's avatar
Weng Xuetian committed
681
    skk->update_candidate = false;
682

Weng Xuetian's avatar
Weng Xuetian committed
683 684 685 686
    FcitxMessages* preedit = (FcitxInstanceICSupportPreedit(skk->owner, FcitxInstanceGetCurrentIC(skk->owner)))
                                ? FcitxInputStateGetClientPreedit(input)
                                : FcitxInputStateGetPreedit(input);

687

Weng Xuetian's avatar
Weng Xuetian committed
688
    const gchar* preeditString = skk_context_get_preedit(skk->context);
689 690 691
    size_t len = strlen(preeditString);
    if (len > 0) {
        guint offset, nchars;
Weng Xuetian's avatar
Weng Xuetian committed
692
        skk_context_get_preedit_underline(skk->context, &offset, &nchars);
693 694

        if (nchars > 0) {
Weng Xuetian's avatar
Weng Xuetian committed
695
            const gchar* preeditString = skk_context_get_preedit(skk->context);
696 697 698
            char* off = fcitx_utf8_get_nth_char(preeditString, offset);
            if (offset > 0) {
                char* left = strndup(preeditString, off - preeditString);
Weng Xuetian's avatar
Weng Xuetian committed
699
                FcitxMessagesAddMessageAtLast(preedit, MSG_OTHER, "%s", left);
700 701 702 703
                fcitx_utils_free(left);
            }
            char* right = fcitx_utf8_get_nth_char(off, nchars);
            char* middle = strndup(off, right - off);
Weng Xuetian's avatar
Weng Xuetian committed
704
            FcitxMessagesAddMessageAtLast(preedit, MSG_HIGHLIGHT, "%s", middle);
705 706 707
            fcitx_utils_free(middle);

            if (*right != 0) {
Weng Xuetian's avatar
Weng Xuetian committed
708
                FcitxMessagesAddMessageAtLast(preedit, MSG_OTHER, "%s", right);
709 710 711
            }
        }
        else {
Weng Xuetian's avatar
Weng Xuetian committed
712
            FcitxMessagesAddMessageAtLast(preedit, MSG_OTHER, "%s", preeditString);
713 714 715 716 717 718
        }
    }

    FcitxInputStateSetClientCursorPos(input, len);
    skk->updatePreedit = false;

Yichao Yu's avatar
Yichao Yu committed
719 720 721 722 723 724 725
    return IRV_DISPLAY_CANDWORDS;
}

static void
FcitxSkkReset(void *arg)
{
    FcitxSkk *skk = (FcitxSkk*)arg;
Weng Xuetian's avatar
Weng Xuetian committed
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
    skk_context_reset(skk->context);
}

static void FcitxSkkReloadConfig(void* arg)
{
    FcitxSkk *skk = (FcitxSkk*)arg;
    SkkLoadConfig(&skk->config);
    FcitxSkkApplyConfig(skk);
    FcitxSkkLoadRule(skk);
    FcitxSkkLoadDictionary(skk);
}

void FcitxSkkApplyConfig(FcitxSkk* skk)
{
    SkkCandidateList* skkCandidates = skk_context_get_candidates(skk->context);
    skk_candidate_list_set_page_start(skkCandidates, skk->config.nTriggersToShowCandWin);
    skk_candidate_list_set_page_size(skkCandidates, skk->config.pageSize);
    skk_context_set_period_style(skk->context, skk->config.punctuationStyle);
    skk_context_set_egg_like_newline(skk->context, skk->config.eggLikeNewLine);
Yichao Yu's avatar
Yichao Yu committed
745
}