/*
  preedit.c
*/

#include <stdlib.h>
#include "iiimcfint.h"

IIIMF_status
iiimcf_toggle_preedit(
    IIIMCF_context_rec *pc,
    int flag
)
{
    if (flag && !IIIMCF_IS_ENABLED(pc, IIIMCF_CONTEXT_PREEDIT_ENABLED)) {
	IIIMCF_SET_STATE(pc, IIIMCF_CONTEXT_PREEDIT_ENABLED);
	IIIMCF_SET_STATE_CHANGE(pc, IIIMCF_STATE_PREEDIT_CHANGED);
	return iiimcf_store_simple_event(pc, IIIMCF_EVENT_TYPE_UI_PREEDIT_START);
    } else if (!flag && IIIMCF_IS_ENABLED(pc, IIIMCF_CONTEXT_PREEDIT_ENABLED)) {
	IIIMCF_RESET_STATE(pc, IIIMCF_CONTEXT_PREEDIT_ENABLED);
	IIIMCF_SET_STATE_CHANGE(pc, IIIMCF_STATE_PREEDIT_CHANGED);
	return iiimcf_store_simple_event(pc, IIIMCF_EVENT_TYPE_UI_PREEDIT_DONE);
    }

    return IIIMF_STATUS_SUCCESS;
}

IIIMF_status
iiimcf_update_preedit(
    IIIMCF_context_rec *pc,
    IIIMP_message *pmes
)
{
    IIIMF_status st;
    ASSERT(pmes->opcode == IM_PREEDIT_DRAW);

    st = iiimcf_update_text_by_preedit_draw(&pc->preedit_text, pmes);
    if (st != IIIMF_STATUS_SUCCESS) return st;

    /* 
       Strictly speaking, we should not enable status here.
       However, Solaris Chinese LEs never send IM_PREEDIT_START,
       we cannot help enabling preedit by IM_PREEDIT_DRAW as well...
       See iiimcf_update_status() also.
     */
    if (!IIIMCF_IS_ENABLED(pc, IIIMCF_CONTEXT_PREEDIT_ENABLED)) {
	st = iiimcf_toggle_preedit(pc, 1);
	if (st != IIIMF_STATUS_SUCCESS) return st;
    }

    pc->preedit_caret_position = pmes->v.preedit_draw.caret;

    IIIMCF_SET_STATE_CHANGE(pc, IIIMCF_STATE_PREEDIT_CHANGED);

    return iiimcf_store_simple_event(pc, IIIMCF_EVENT_TYPE_UI_PREEDIT_CHANGE);
}

IIIMF_status
iiimcf_get_preedit_text(
    IIIMCF_context context,
    IIIMCF_text *ptext,
    int *pcaret_position
)
{
    IIIMCF_context_rec *pc = (IIIMCF_context_rec*) context;

    if (IIIMCF_IS_IC_INVALID(pc)) return IIIMF_STATUS_IC_INVALID;
    if ((!IIIMCF_IS_ENABLED(pc, IIIMCF_CONTEXT_PREEDIT_ENABLED))
	|| (!IIIMCF_IS_VALID_TEXT(&pc->preedit_text)))
	return IIIMF_STATUS_NO_PREEDIT;
    
    *ptext = &pc->preedit_text;
    *pcaret_position = pc->preedit_caret_position;

    return IIIMF_STATUS_SUCCESS;
}

/* Local Variables: */
/* c-file-style: "iiim-project" */
/* End: */
