Avoiding suggestion bar blink when focusing in number layout
[framework/uifw/ise-engine-tables.git] / src / scim_table_imengine.cpp
1 /** @file scim_table_imengine.cpp
2  * implementation of class TableInstance.
3  */
4
5 /*
6  * Smart Common Input Method
7  * 
8  * Copyright (c) 2002-2005 James Su <suzhe@tsinghua.org.cn>
9  * Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24  *
25  * $Id: scim_table_imengine.cpp,v 1.12 2006/01/12 08:43:29 suzhe Exp $
26  *
27  * Modifications by Samsung Electronics Co., Ltd.
28  *
29  * 1.Added auto commit feature for mobile user
30  */
31
32 #define Uses_STL_AUTOPTR
33 #define Uses_STL_FUNCTIONAL
34 #define Uses_STL_VECTOR
35 #define Uses_STL_IOSTREAM
36 #define Uses_STL_FSTREAM
37 #define Uses_STL_ALGORITHM
38 #define Uses_STL_MAP
39 #define Uses_STL_UTILITY
40 #define Uses_STL_IOMANIP
41 #define Uses_C_STDIO
42 #define Uses_SCIM_UTILITY
43 #define Uses_SCIM_IMENGINE
44 #define Uses_SCIM_ICONV
45 #define Uses_SCIM_CONFIG_BASE
46 #define Uses_SCIM_CONFIG_PATH
47 #define Uses_SCIM_LOOKUP_TABLE
48
49 #include <dirent.h>
50 #include <sys/types.h>
51 #include <sys/stat.h>
52 #include <unistd.h>
53 #include <scim.h>
54 #include <set>
55
56 #include <Ecore_IMF.h>
57
58 #include "scim_table_imengine.h"
59 #include "scim_table_private.h"
60
61 #define scim_module_init table_LTX_scim_module_init
62 #define scim_module_exit table_LTX_scim_module_exit
63 #define scim_imengine_module_init table_LTX_scim_imengine_module_init
64 #define scim_imengine_module_create_factory table_LTX_scim_imengine_module_create_factory
65
66 #define SCIM_TABLE_SAVE_PERIOD       300
67
68 #define SCIM_TABLE_MAX_TABLE_NUMBER  256
69 #define SCIM_TABLE_MAX_INPUTTED_KEYS  16
70
71 #define SCIM_CONFIG_IMENGINE_TABLE_FULL_WIDTH_PUNCT_KEY   "/IMEngine/Table/FullWidthPunctKey"
72 #define SCIM_CONFIG_IMENGINE_TABLE_FULL_WIDTH_LETTER_KEY  "/IMEngine/Table/FullWidthLetterKey"
73 #define SCIM_CONFIG_IMENGINE_TABLE_MODE_SWITCH_KEY        "/IMEngine/Table/ModeSwitchKey"
74 #define SCIM_CONFIG_IMENGINE_TABLE_ADD_PHRASE_KEY         "/IMEngine/Table/AddPhraseKey"
75 #define SCIM_CONFIG_IMENGINE_TABLE_DEL_PHRASE_KEY         "/IMEngine/Table/DeletePhraseKey"
76 #define SCIM_CONFIG_IMENGINE_TABLE_SHOW_PROMPT            "/IMEngine/Table/ShowPrompt"
77 #define SCIM_CONFIG_IMENGINE_TABLE_USER_TABLE_BINARY      "/IMEngine/Table/UserTableBinary"
78 #define SCIM_CONFIG_IMENGINE_TABLE_USER_PHRASE_FIRST      "/IMEngine/Table/UserPhraseFirst"
79 #define SCIM_CONFIG_IMENGINE_TABLE_LONG_PHRASE_FIRST      "/IMEngine/Table/LongPhraseFirst"
80 #define SCIM_CONFIG_IMENGINE_TABLE_SHOW_KEY_HINT          "/IMEngine/Table/ShowKeyHint"
81
82 #define SCIM_PROP_STATUS                                  "/IMEngine/Table/Status"
83 #define SCIM_PROP_LETTER                                  "/IMEngine/Table/Letter"
84 #define SCIM_PROP_PUNCT                                   "/IMEngine/Table/Punct"
85
86 #define SCIM_FULL_LETTER_ICON                             (SCIM_ICONDIR "/full-letter.png")
87 #define SCIM_HALF_LETTER_ICON                             (SCIM_ICONDIR "/half-letter.png")
88 #define SCIM_FULL_PUNCT_ICON                              (SCIM_ICONDIR "/full-punct.png")
89 #define SCIM_HALF_PUNCT_ICON                              (SCIM_ICONDIR "/half-punct.png")
90
91 #define SCIM_TABLE_ICON_FILE                              (SCIM_ICONDIR "/table.png")
92
93
94 using namespace scim;
95
96 static unsigned int _scim_number_of_tables = 0;
97
98 static Pointer <TableFactory> _scim_table_factories [SCIM_TABLE_MAX_TABLE_NUMBER];
99
100 static std::vector<String> _scim_sys_table_list;
101 static std::vector<String> _scim_user_table_list;
102
103 static ConfigPointer _scim_config;
104 char g_common_symbol[]={'#','$','%','^','&','*','@'};
105
106 static void
107 _get_table_list (std::vector<String> &table_list, const String &path)
108 {
109     table_list.clear ();
110
111     DIR *dir = opendir (path.c_str ());
112     if (dir != NULL) {
113         struct dirent *file = readdir (dir);
114         while (file != NULL) {
115             struct stat filestat;
116             String absfn = path + SCIM_PATH_DELIM_STRING + file->d_name;
117             stat (absfn.c_str (), &filestat);
118
119             if (S_ISREG (filestat.st_mode))
120                 table_list.push_back (absfn);
121
122             file = readdir (dir);
123         }
124         closedir (dir);        
125     }
126 }
127
128 extern "C" {
129     void scim_module_init (void)
130     {
131         bindtextdomain (GETTEXT_PACKAGE, SCIM_TABLE_LOCALEDIR);
132         bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
133     }
134
135     void scim_module_exit (void)
136     {
137         for (int i=0; i<_scim_number_of_tables; ++i)
138             _scim_table_factories [i].reset ();
139
140         _scim_config.reset ();
141     }
142
143     unsigned int scim_imengine_module_init (const ConfigPointer &config)
144     {
145         _scim_config = config;
146
147         _get_table_list (_scim_sys_table_list, SCIM_TABLE_SYSTEM_TABLE_DIR);
148         _get_table_list (_scim_user_table_list, scim_get_home_dir () + SCIM_TABLE_USER_TABLE_DIR);
149
150         _scim_number_of_tables = _scim_sys_table_list.size () + _scim_user_table_list.size (); 
151
152         return _scim_number_of_tables; 
153     }
154
155     IMEngineFactoryPointer scim_imengine_module_create_factory (unsigned int index)
156     {
157         if (index >= _scim_number_of_tables) return 0;
158
159         TableFactory *factory = 0;
160
161         try {
162             factory = new TableFactory (_scim_config);
163
164             if (index < _scim_sys_table_list.size ())
165                 factory->load_table (_scim_sys_table_list [index], false);
166             else
167                 factory->load_table (_scim_user_table_list [index - _scim_sys_table_list.size ()], true);
168
169             if (!factory->valid ())
170                 throw IMEngineError ("Table load failed!");
171
172             return IMEngineFactoryPointer (factory);
173
174         } catch (...) {
175             delete factory;
176             return IMEngineFactoryPointer (0);
177         }
178     }
179 }
180
181 // implementation of Table
182 TableFactory::TableFactory (const ConfigPointer &config)
183     : m_config (config),
184       m_is_user_table (false),
185       m_show_prompt (false),
186       m_show_key_hint (false),
187       m_user_table_binary (false),
188       m_user_phrase_first (false),
189       m_long_phrase_first (false),
190       m_last_time ((time_t)0),
191       m_status_property (SCIM_PROP_STATUS, ""),
192       m_letter_property (SCIM_PROP_LETTER, _("Full/Half Letter")),
193       m_punct_property (SCIM_PROP_PUNCT, _("Full/Half Punct"))
194 {
195     init (m_config);
196
197     m_status_property.set_tip (_("The status of the current input method. Click to change it."));
198     m_letter_property.set_tip (_("The input mode of the letters. Click to toggle between half and full."));
199     m_punct_property.set_tip (_("The input mode of the puncutations. Click to toggle between half and full."));
200
201     if (!m_config.null ())
202         m_reload_signal_connection = m_config->signal_connect_reload (slot (this, &TableFactory::init));
203 }
204
205 void
206 TableFactory::init (const ConfigPointer &config)
207 {
208     String str;
209
210     SCIM_DEBUG_IMENGINE (1) << "Load configuration.\n";
211
212     if (!config.null ()) {
213         //Read full width punctuation keys
214         str = config->read (String (SCIM_CONFIG_IMENGINE_TABLE_FULL_WIDTH_PUNCT_KEY), String (""));
215
216         scim_string_to_key_list (m_full_width_punct_keys, str);
217
218         //Read full width letter keys
219         str = config->read (String (SCIM_CONFIG_IMENGINE_TABLE_FULL_WIDTH_LETTER_KEY), String (""));
220
221         scim_string_to_key_list (m_full_width_letter_keys, str);
222
223         //Read mode switch keys
224         str = config->read (String (SCIM_CONFIG_IMENGINE_TABLE_MODE_SWITCH_KEY), String (""));
225
226         scim_string_to_key_list (m_mode_switch_keys, str);
227
228         //Read add phrase keys
229         str = config->read (String (SCIM_CONFIG_IMENGINE_TABLE_ADD_PHRASE_KEY), String ("Control+a,Control+equal"));
230
231         scim_string_to_key_list (m_add_phrase_keys, str);
232
233         //Read delete phrase keys
234         str = config->read (String (SCIM_CONFIG_IMENGINE_TABLE_DEL_PHRASE_KEY), String ("Control+d,Control+minus"));
235
236         scim_string_to_key_list (m_del_phrase_keys, str);
237
238         m_show_prompt = config->read (String (SCIM_CONFIG_IMENGINE_TABLE_SHOW_PROMPT), false);
239
240         m_show_key_hint = config->read (String (SCIM_CONFIG_IMENGINE_TABLE_SHOW_KEY_HINT), false);
241
242         m_user_phrase_first = config->read (String (SCIM_CONFIG_IMENGINE_TABLE_USER_PHRASE_FIRST), false);
243
244         m_long_phrase_first = config->read (String (SCIM_CONFIG_IMENGINE_TABLE_LONG_PHRASE_FIRST), false);
245
246         m_user_table_binary = config->read (String (SCIM_CONFIG_IMENGINE_TABLE_USER_TABLE_BINARY), false);
247     }
248
249     m_last_time = time (NULL);
250 }
251
252 TableFactory::~TableFactory ()
253 {
254     save ();
255     m_reload_signal_connection.disconnect ();
256 }
257
258 WideString
259 TableFactory::get_name () const
260 {
261     return m_table.get_name (scim_get_current_locale ());
262 }
263
264 WideString
265 TableFactory::get_authors () const
266 {
267     return m_table.get_author ();
268 }
269
270 WideString
271 TableFactory::get_credits () const
272 {
273     return WideString ();
274 }
275
276 WideString
277 TableFactory::get_help () const
278 {
279     WideString help;
280
281     std::vector<KeyEvent> keys, keys2;
282
283     String full_width_letter;
284     String full_width_punct;
285     String mode_switch;
286     String add_phrase;
287     String del_phrase;
288
289     keys = m_full_width_letter_keys;
290     keys2 = m_table.get_full_width_letter_keys ();
291     keys.insert (keys.end (), keys2.begin (), keys2.end ());
292     keys.erase (std::unique (keys.begin (), keys.end ()), keys.end ());
293     scim_key_list_to_string (full_width_letter, keys);
294
295     keys = m_full_width_punct_keys;
296     keys2 = m_table.get_full_width_punct_keys ();
297     keys.insert (keys.end (), keys2.begin (), keys2.end ());
298     keys.erase (std::unique (keys.begin (), keys.end ()), keys.end ());
299     scim_key_list_to_string (full_width_punct, keys);
300
301     keys = m_mode_switch_keys;
302     keys2 = m_table.get_mode_switch_keys ();
303     keys.insert (keys.end (), keys2.begin (), keys2.end ());
304     keys.erase (std::unique (keys.begin (), keys.end ()), keys.end ());
305     scim_key_list_to_string (mode_switch, keys);
306
307     scim_key_list_to_string (add_phrase, m_add_phrase_keys);
308     scim_key_list_to_string (del_phrase, m_del_phrase_keys);
309
310     return utf8_mbstowcs (
311         String (_("Hot Keys:\n\n  ")) +
312         full_width_letter + String (":\n") +
313         String (_("    Switch between full/half width letter mode.\n\n  ")) +
314         full_width_punct + String (":\n") +
315         String (_("    Switch between full/half width punctuation mode.\n\n  ")) +
316         mode_switch + String (":\n") +
317         String (_("    Switch between Forward/Input mode.\n\n  ")) +
318         add_phrase + String (":\n") +
319         String (_("    Add a new phrase.\n\n  ")) +
320         del_phrase + String (":\n") +
321         String (_("    Delete the selected phrase.\n\n")) +
322         String (_("  Control+Down:\n    Move lookup cursor to next shorter phrase\n"
323                   "    Only available when LongPhraseFirst option is set.\n\n")) +
324         String (_("  Control+Up:\n    Move lookup cursor to previous longer phrase\n"
325                   "    Only available when LongPhraseFirst option is set.\n\n")) +
326         String (_("  Esc:\n    reset the input method.\n\n\n")) +
327         String (_("How to add a phrase:\n"
328                   "    Input the new phrase as normal, then press the\n"
329                   "  hot key. A hint will be shown to let you input a key\n"
330                   "  for this phrase.\n"
331                   "    Input a key then press the space bar.\n"
332                   "  A hint will be shown to indicate whether\n"
333                   "  the phrase was added sucessfully.\n"))
334         );
335 }
336
337 String
338 TableFactory::get_uuid () const
339 {
340     return m_table.get_uuid ();
341 }
342
343 String
344 TableFactory::get_icon_file () const
345 {
346     String file = m_table.get_icon_file ();
347
348     return file.length () ? file : String (SCIM_TABLE_ICON_FILE);
349 }
350
351 IMEngineInstancePointer
352 TableFactory::create_instance (const String& encoding, int id)
353 {
354     return new TableInstance (this, encoding, id);
355 }
356
357 bool
358 TableFactory::load_table (const String &table_file, bool user_table)
359 {
360     if (!table_file.length ()) return false;
361
362     m_table_filename = table_file;
363     m_is_user_table = user_table;
364
365     if (user_table) {
366         if (!m_table.init ("", m_table_filename, "")) return false;
367     } else {
368         if (!m_table.init (m_table_filename,
369                            get_sys_table_user_file (),
370                            get_sys_table_freq_file ()))
371             return false;
372     }
373
374     set_languages (m_table.get_languages ());
375
376     return m_table.valid ();
377 }
378
379 void
380 TableFactory::refresh (bool rightnow)
381 {
382     time_t cur_time = time (NULL);
383
384     if (rightnow || cur_time < m_last_time || cur_time - m_last_time > SCIM_TABLE_SAVE_PERIOD) {
385         m_last_time = cur_time;
386         save ();
387     }
388 }
389
390 void
391 TableFactory::save ()
392 {
393     if (!m_table.valid () || !m_table.updated ()) return;
394
395     if (m_is_user_table)
396         m_table.save ("", m_table_filename, "", m_user_table_binary);
397     else
398         m_table.save ("", get_sys_table_user_file (), get_sys_table_freq_file (), m_user_table_binary);
399 }
400
401 String
402 TableFactory::get_sys_table_freq_file ()
403 {
404     String fn, tf;
405     String::size_type pos;
406
407     if (m_table_filename.length ()) {
408         pos = m_table_filename.rfind (SCIM_PATH_DELIM);
409
410         if (pos != String::npos)
411             tf = m_table_filename.substr (pos+1);
412         else
413             tf = m_table_filename;
414
415         fn = scim_get_home_dir () + SCIM_TABLE_SYSTEM_UPDATE_TABLE_DIR;
416
417         if (access (fn.c_str (), R_OK | W_OK) != 0) {
418             if (!scim_make_dir (fn))
419                 return String ();
420         }
421
422         fn = fn + SCIM_PATH_DELIM_STRING + tf + ".freq";
423     }
424     return fn;
425 }
426
427 String
428 TableFactory::get_sys_table_user_file ()
429 {
430     String fn, tf;
431     String::size_type pos;
432
433     if (m_table_filename.length ()) {
434         pos = m_table_filename.rfind (SCIM_PATH_DELIM);
435
436         if (pos != String::npos)
437             tf = m_table_filename.substr (pos+1);
438         else
439             tf = m_table_filename;
440
441         fn = scim_get_home_dir () + SCIM_TABLE_SYSTEM_UPDATE_TABLE_DIR;
442
443         if (access (fn.c_str (), R_OK | W_OK) != 0) {
444             if (!scim_make_dir (fn))
445                 return String ();
446         }
447
448         fn = fn + SCIM_PATH_DELIM_STRING + tf + ".user";
449     }
450     return fn;
451 }
452
453
454 // implementation of TableInstance
455 TableInstance::TableInstance (TableFactory *factory,
456                                             const String& encoding,
457                                             int id)
458     : IMEngineInstanceBase (factory, encoding, id),
459       m_factory (factory),
460       m_double_quotation_state (false),
461       m_single_quotation_state (false),
462       m_forward (false),
463       m_focused (false),
464       m_inputing_caret (0),
465       m_inputing_key (0),
466       m_iconv (encoding)
467 {
468     m_full_width_letter [0] = m_factory->m_table.is_def_full_width_letter ();
469     m_full_width_letter [1] = false;
470
471     m_full_width_punct [0] = m_factory->m_table.is_def_full_width_punct ();
472     m_full_width_punct [1] = false;
473
474     char buf [2] = { 0, 0 };
475
476     std::vector <KeyEvent>   keys = m_factory->m_table.get_select_keys ();
477     std::vector <WideString> labels;
478
479     for (size_t i = 0; i < keys.size (); ++i) {
480         buf [0] = keys [i].get_ascii_code ();
481         labels.push_back (utf8_mbstowcs (buf));
482     }
483
484     m_lookup_table.set_candidate_labels (labels);
485     m_lookup_table.set_page_size        (keys.size ());
486     m_lookup_table.show_cursor ();
487
488     AttributeList attrs;
489     for (int i = 0;i < sizeof(g_common_symbol)/sizeof(char);i++) {
490         char _str[2]={g_common_symbol[i],0};
491         m_common_lookup_table.append_candidate (utf8_mbstowcs ((const char*)_str),attrs);
492     }
493 }
494
495 TableInstance::~TableInstance ()
496 {
497 }
498
499 bool
500 TableInstance::process_key_event (const KeyEvent& rawkey)
501 {
502     KeyEvent key = rawkey.map_to_layout (m_factory->m_table.get_keyboard_layout ());
503
504     bool ret = false;
505
506     if (!m_focused) return false;
507
508     // capture the mode switch key events
509     if (match_key_event (m_factory->m_mode_switch_keys, key) ||
510         match_key_event (m_factory->m_table.get_mode_switch_keys (), key)) {
511         m_forward = !m_forward;
512         refresh_status_property ();
513         refresh_letter_property ();
514         refresh_punct_property ();
515         reset ();
516         ret = true;
517     }
518
519     // toggle full width punctuation mode
520     else if (match_key_event (m_factory->m_full_width_punct_keys, key) ||
521              match_key_event (m_factory->m_table.get_full_width_punct_keys (), key)) {
522         trigger_property (SCIM_PROP_PUNCT);
523         ret = true;
524     }
525
526     // toggle full width letter mode
527     else if (match_key_event (m_factory->m_full_width_letter_keys, key) ||
528              match_key_event (m_factory->m_table.get_full_width_letter_keys (), key)) {
529         trigger_property (SCIM_PROP_LETTER);
530         ret = true;
531     }
532
533     // discard the key release event.
534     else if (key.is_key_release ()) {
535         ret = true;
536     }
537
538     // process the key press event, if not in forward mode.
539     else if (!m_forward) {
540         // First reset add phrase mode.
541         if (m_add_phrase_mode > 1) {
542             m_add_phrase_mode = 0;
543             refresh_aux_string ();
544         }
545
546         //reset key
547         if (key.code == SCIM_KEY_Escape && key.mask == 0) {
548             if (m_inputted_keys.size () == 0 && m_add_phrase_mode != 1)
549                 ret = false;
550             else {
551                 reset ();
552                 ret = true;
553             }
554         }
555
556         //caret left
557         else if (key.code == SCIM_KEY_Left && key.mask == 0)
558             ret = caret_left ();
559
560         //caret right
561         else if (key.code == SCIM_KEY_Right && key.mask == 0)
562             ret = caret_right ();
563
564         //caret home 
565         else if (key.code == SCIM_KEY_Home && key.mask == 0)
566             ret = caret_home ();
567
568         //caret end
569         else if (key.code == SCIM_KEY_End && key.mask == 0)
570             ret = caret_end ();
571
572         //lookup table cursor up
573         else if (key.code == SCIM_KEY_Up && key.mask == 0)
574             ret = lookup_cursor_up ();
575
576         //lookup table cursor down
577         else if (key.code == SCIM_KEY_Down && key.mask == 0)
578             ret = lookup_cursor_down ();
579
580         //lookup table cursor up to longer phrase
581         else if (key.code == SCIM_KEY_Up && key.mask == SCIM_KEY_ControlMask &&
582                  m_factory->m_long_phrase_first && !m_factory->m_user_phrase_first)
583             ret = lookup_cursor_up_to_longer ();
584
585         //lookup table cursor down
586         else if (key.code == SCIM_KEY_Down && key.mask == SCIM_KEY_ControlMask &&
587                  m_factory->m_long_phrase_first && !m_factory->m_user_phrase_first)
588             ret = lookup_cursor_down_to_shorter ();
589
590         //backspace key
591         else if (key.code == SCIM_KEY_BackSpace && key.mask == 0)
592             ret = erase ();
593
594         //delete key
595         else if (key.code == SCIM_KEY_Delete && key.mask == 0)
596             ret = erase (false);
597
598         //add new phrase
599         else if (!m_inputted_keys.size () && m_last_committed.length () &&
600             match_key_event (m_factory->m_add_phrase_keys, key)) {
601             m_add_phrase_mode = 1;
602             refresh_aux_string ();
603             ret = true;
604         }
605
606         //delete phrase
607         else if (match_key_event (m_factory->m_del_phrase_keys, key)) {
608             if (delete_phrase ())
609                 ret = true;
610         }
611
612         // other situation
613         else {
614             ret = false;
615
616             //select lookup table
617             int pos = m_factory->m_table.get_select_key_pos (key);
618
619             // If there is a new empty key (a split char was inserted),
620             // then try to select lookup table first.
621             // Otherwise try to insert the char first.
622             if (m_inputted_keys.size () && !m_inputted_keys [m_inputing_key].length ()) {
623                 if (pos >= 0 && pos < m_lookup_table.get_current_page_size ())
624                     ret = lookup_select (pos);
625
626                 // insert char
627                 if (!ret && (key.mask & (~ (SCIM_KEY_ShiftMask + SCIM_KEY_CapsLockMask))) == 0)
628                     ret = insert (key.get_ascii_code ());
629             } else {
630                 // insert char
631                 if ((key.mask & (~ (SCIM_KEY_ShiftMask + SCIM_KEY_CapsLockMask))) == 0 &&
632                     test_insert (key.get_ascii_code ()))
633                     ret = insert (key.get_ascii_code ());
634
635                 if (!ret && pos >= 0 && pos < m_lookup_table.get_current_page_size ())
636                     ret = lookup_select (pos);
637
638                 // insert char finally.
639                 if (!ret && (key.mask & (~ (SCIM_KEY_ShiftMask + SCIM_KEY_CapsLockMask))) == 0)
640                     ret = insert (key.get_ascii_code ());
641             }
642
643             //lookup table page up
644             if (!ret && match_key_event (m_factory->m_table.get_page_up_keys (), key))
645                 ret = lookup_page_up ();
646
647             //lookup table page down
648             if (!ret && match_key_event (m_factory->m_table.get_page_down_keys (), key))
649                 ret = lookup_page_down ();
650
651             //space hit
652             if (!ret && match_key_event (m_factory->m_table.get_commit_keys (), key))
653                 ret = space_hit ();
654
655             //enter hit
656             if (!ret && match_key_event (m_factory->m_table.get_forward_keys (), key))
657                 ret = enter_hit ();
658         }
659     }
660
661     if (!ret && (key.mask & (~ (SCIM_KEY_ShiftMask + SCIM_KEY_CapsLockMask))) == 0 &&
662         key.get_ascii_code ())
663         ret = post_process (key.get_ascii_code ());
664
665     m_prev_key = key;
666
667     return ret;
668 }
669
670 void
671 TableInstance::select_candidate (unsigned int item)
672 {
673
674     if (m_inputted_keys.size () == 0
675         && m_lookup_table.number_of_candidates() == 0
676         && item < sizeof(g_common_symbol)/sizeof(char)) {
677         char _str[2]={g_common_symbol[item],0};
678         commit_string(utf8_mbstowcs(_str));
679         return;
680     }
681     lookup_select (item);
682 }
683
684 void
685 TableInstance::update_lookup_table_page_size (unsigned int page_size)
686 {
687     if (page_size > 0)
688         m_lookup_table.set_page_size (page_size);
689 }
690
691 void
692 TableInstance::lookup_table_page_up ()
693 {
694     lookup_page_up ();
695 }
696
697 void
698 TableInstance::lookup_table_page_down ()
699 {
700     lookup_page_down ();
701 }
702
703 void
704 TableInstance::move_preedit_caret (unsigned int pos)
705 {
706     uint32 len = 0;
707     size_t i;
708
709     for (i=0; i<m_converted_strings.size (); ++i) {
710         if (pos >= len && pos < len + m_converted_strings [i].length ()) {
711             m_inputing_key = i;
712             m_inputing_caret = m_inputted_keys [i].length ();
713
714             m_converted_strings.erase (m_converted_strings.begin () + i, m_converted_strings.end ());
715             m_converted_indexes.erase (m_converted_indexes.begin () + i, m_converted_indexes.end ());
716
717             refresh_lookup_table ();
718             refresh_preedit ();
719             refresh_aux_string ();
720
721             return;
722         }
723         len += m_converted_strings [i].length ();
724     }
725
726     if (m_factory->m_table.is_auto_fill () &&
727         m_inputing_key == m_inputted_keys.size () - 1 &&
728         m_inputing_caret == m_inputted_keys [m_inputing_key].length () &&
729         m_converted_strings.size () == m_inputing_key &&
730         m_lookup_table.number_of_candidates ()) {
731
732         uint32 offset = m_lookup_table_indexes [m_lookup_table.get_cursor_pos ()];
733         size_t phlen  = m_factory->m_table.get_phrase_length (offset);
734
735         if (pos >= len && pos < len + phlen) {
736             m_inputing_caret = 0;
737             refresh_lookup_table (true, false);
738             refresh_preedit ();
739             return;
740         }
741     } else {
742         if (m_converted_strings.size ()) {
743             ++len;
744             if (pos < len) ++pos;
745         }
746
747         for (i=m_converted_strings.size (); i<m_inputted_keys.size (); ++i) {
748             if (pos >= len && pos <= len + m_inputted_keys [i].length ()) {
749                 m_inputing_key = i;
750                 m_inputing_caret = pos - len;
751
752                 refresh_lookup_table (true, false);
753                 refresh_preedit ();
754                 refresh_aux_string ();
755                 return;
756             }
757
758             len += (m_inputted_keys [i].length () +1);
759         }
760     }
761 }
762
763 void
764 TableInstance::reset ()
765 {
766     if (m_inputted_keys.size () && m_preedit_string.size()) {
767         commit_string (m_preedit_string);
768     }
769     m_double_quotation_state = false;
770     m_single_quotation_state = false;
771
772     m_lookup_table.clear ();
773
774     std::vector<String> ().swap (m_inputted_keys);
775
776     std::vector<WideString> ().swap (m_converted_strings);
777
778     std::vector<uint32> ().swap (m_converted_indexes);
779
780     std::vector<uint32> ().swap (m_lookup_table_indexes);
781
782     m_add_phrase_mode = 0;
783
784     m_last_committed = WideString ();
785
786     m_inputing_caret = 0;
787     m_inputing_key = 0;
788
789     m_iconv.set_encoding (get_encoding ());
790     if (!m_forward) {
791         refresh_lookup_table (true, true);
792         if (m_focused)
793             show_lookup_table ();
794     } else {
795         hide_lookup_table();
796     }
797     hide_preedit_string ();
798     hide_aux_string ();
799 }
800
801 void
802 TableInstance::focus_in ()
803 {
804     m_focused = true;
805
806     if (m_add_phrase_mode != 1) {
807         m_last_committed = WideString ();
808         m_add_phrase_mode = 0;
809     }
810
811     //refresh_lookup_table (true, false);
812     refresh_preedit ();
813     refresh_aux_string ();
814     initialize_properties ();
815 }
816
817 void
818 TableInstance::focus_out ()
819 {
820     m_focused = false;
821     reset ();
822 }
823
824 void
825 TableInstance::trigger_property (const String &property)
826 {
827     if (property == SCIM_PROP_STATUS) {
828         m_forward = !m_forward;
829         refresh_status_property ();
830         refresh_letter_property ();
831         refresh_punct_property ();
832         reset ();
833     } else if (property == SCIM_PROP_LETTER && m_factory->m_table.is_use_full_width_letter ()) {
834         m_full_width_letter [m_forward?1:0] =
835             !m_full_width_letter [m_forward?1:0];
836         refresh_letter_property ();
837     } else if (property == SCIM_PROP_PUNCT && m_factory->m_table.is_use_full_width_punct ()) {
838         m_full_width_punct [m_forward?1:0] = 
839             !m_full_width_punct [m_forward?1:0];
840         refresh_punct_property ();
841     }
842 }
843  
844 void
845 TableInstance::set_layout (unsigned int layout)
846 {
847     switch (layout)
848     {
849         case ECORE_IMF_INPUT_PANEL_LAYOUT_NORMAL:
850         case ECORE_IMF_INPUT_PANEL_LAYOUT_NUMBER:
851         case ECORE_IMF_INPUT_PANEL_LAYOUT_EMAIL:
852         case ECORE_IMF_INPUT_PANEL_LAYOUT_URL:
853             refresh_lookup_table(true,false);
854             show_lookup_table ();
855             m_forward = false;
856             break;
857         default:
858             hide_lookup_table ();
859             m_forward = true;
860     }
861 }
862
863 void
864 TableInstance::initialize_properties ()
865 {
866     PropertyList proplist;
867
868     proplist.push_back (m_factory->m_status_property);
869
870     if (m_factory->m_table.is_use_full_width_letter ())
871         proplist.push_back (m_factory->m_letter_property);
872
873     if (m_factory->m_table.is_use_full_width_punct ())
874         proplist.push_back (m_factory->m_punct_property);
875
876     register_properties (proplist);
877
878     refresh_status_property ();
879     refresh_letter_property ();
880     refresh_punct_property ();
881 }
882
883 void
884 TableInstance::refresh_status_property ()
885 {
886     if (m_focused) {
887         if (m_forward)
888             m_factory->m_status_property.set_label (_("En"));
889         else
890             m_factory->m_status_property.set_label (utf8_wcstombs (m_factory->m_table.get_status_prompt ()));
891
892         update_property (m_factory->m_status_property);
893     }
894 }
895
896 void
897 TableInstance::refresh_letter_property ()
898 {
899     if (m_focused && m_factory->m_table.is_use_full_width_letter ()) {
900         m_factory->m_letter_property.set_icon (
901             m_full_width_letter [m_forward?1:0] ? SCIM_FULL_LETTER_ICON : SCIM_HALF_LETTER_ICON);
902         update_property (m_factory->m_letter_property);
903     }
904 }
905
906 void
907 TableInstance::refresh_punct_property ()
908 {
909     if (m_focused && m_factory->m_table.is_use_full_width_punct ()) {
910         m_factory->m_punct_property.set_icon (
911             m_full_width_punct [m_forward?1:0] ? SCIM_FULL_PUNCT_ICON : SCIM_HALF_PUNCT_ICON);
912         update_property (m_factory->m_punct_property);
913     }
914 }
915
916 bool
917 TableInstance::caret_left ()
918 {
919     if (m_inputted_keys.size ()) {
920         if (m_inputing_caret > 0) {
921             --m_inputing_caret;
922             refresh_lookup_table (true, false);
923         } else if (m_inputing_key > 0) {
924             --m_inputing_key;
925             m_inputing_caret = m_inputted_keys [m_inputing_key].length ();
926
927             if (m_converted_strings.size () > m_inputing_key) {
928                 m_converted_strings.pop_back ();
929                 m_converted_indexes.pop_back ();
930                 refresh_lookup_table ();
931             } else {
932                 refresh_lookup_table (true, false);
933             }
934         } else {
935             return caret_end ();
936         }
937
938         refresh_preedit ();
939         refresh_aux_string ();
940         return true;
941     }
942     return false;
943 }
944
945 bool
946 TableInstance::caret_right ()
947 {
948     if (m_inputted_keys.size ()) {
949         if (m_inputing_caret < m_inputted_keys [m_inputing_key].size ()) {
950             ++m_inputing_caret;
951         } else if (m_inputing_key < m_inputted_keys.size () - 1) {
952             ++m_inputing_key;
953             m_inputing_caret = 0;
954         } else {
955             return caret_home ();
956         }
957         refresh_lookup_table (true, false);
958         refresh_preedit ();
959         refresh_aux_string ();
960         return true;
961     }
962     return false;
963 }
964
965 bool
966 TableInstance::caret_home ()
967 {
968     if (m_inputted_keys.size ()) {
969         m_inputing_key = 0;
970         m_inputing_caret = 0;
971
972         if (m_converted_strings.size ()) {
973             m_converted_strings.clear ();
974             m_converted_indexes.clear ();
975             refresh_lookup_table ();
976         } else {
977             refresh_lookup_table (true, false);
978         }
979
980         refresh_preedit ();
981         refresh_aux_string ();
982         return true;
983     }
984     return false;
985 }
986
987 bool
988 TableInstance::caret_end ()
989 {
990     if (m_inputted_keys.size ()) {
991         m_inputing_key = m_inputted_keys.size () - 1;
992         m_inputing_caret = m_inputted_keys [m_inputing_key].length ();
993
994         refresh_lookup_table (true, false);
995         refresh_preedit ();
996         refresh_aux_string ();
997         return true;
998     }
999     return false;
1000 }
1001
1002 bool
1003 TableInstance::test_insert (char key)
1004 {
1005     if (m_factory->m_table.is_valid_char (key)) {
1006         String newkey;
1007         if (m_inputted_keys.size ()) {
1008             newkey = m_inputted_keys [m_inputing_key];
1009             newkey.insert (newkey.begin () + m_inputing_caret, key);
1010         } else {
1011             newkey.push_back (key);
1012         }
1013
1014         return m_factory->m_table.is_defined_key (newkey);
1015     }
1016     return false;
1017 }
1018
1019 bool
1020 TableInstance::insert (char ch)
1021 {
1022     if (!ch) return false;
1023
1024     String newkey;
1025     uint32 old_inputing_key = m_inputing_key;
1026     bool insert_ok = false;
1027
1028     if (m_inputted_keys.size () - m_converted_strings.size () >
1029         SCIM_TABLE_MAX_INPUTTED_KEYS)
1030         return false;
1031
1032     // If current inputing key is empty, then the last inputing key is the previous key.
1033     if (m_inputted_keys.size () && m_inputing_key && !m_inputted_keys [m_inputing_key].length ())
1034         -- old_inputing_key;
1035
1036     if (m_factory->m_table.is_split_char (ch)) {
1037         // split char is invalid during add phrase mode.
1038         if (m_add_phrase_mode == 1)
1039             return true;
1040         else if (m_inputted_keys.size () == 0)
1041             return false;
1042         else if (m_inputing_key == m_inputted_keys.size () -1 &&
1043                 m_inputted_keys [m_inputing_key].length () &&
1044                 m_inputing_caret == m_inputted_keys [m_inputing_key].length ()) {
1045             ++m_inputing_key;
1046             m_inputing_caret = 0;
1047             m_inputted_keys.insert (m_inputted_keys.begin () + m_inputing_key, String ());
1048         } else {
1049             return false;
1050         }
1051
1052         insert_ok = true;
1053     } else if (m_factory->m_table.is_valid_char (ch)) {
1054         if (m_add_phrase_mode == 1) {
1055             m_inputing_key = 0;
1056             if (!m_inputted_keys.size ()) {
1057                 m_inputted_keys.push_back (String (""));
1058                 m_inputing_caret = 0;
1059             } else if (m_inputted_keys [0].length () >= m_factory->m_table.get_max_key_length ()) {
1060                 return true;
1061             }
1062
1063             m_inputted_keys [0].insert (m_inputted_keys [0].begin () + m_inputing_caret, ch);
1064             ++m_inputing_caret;
1065             insert_ok = true;
1066         } else if (m_inputted_keys.size ()) {
1067             newkey = m_inputted_keys [m_inputing_key];
1068             newkey.insert (newkey.begin () + m_inputing_caret, ch);
1069
1070             if ((m_factory->m_table.is_auto_split () == false ||
1071                  m_factory->m_table.is_defined_key (newkey)) &&
1072                 newkey.length () <= m_factory->m_table.get_max_key_length ()) {
1073                 m_inputted_keys [m_inputing_key] = newkey;
1074                 ++m_inputing_caret;
1075                 insert_ok = true;
1076             } else if (m_inputing_caret == m_inputted_keys [m_inputing_key].length ()) {
1077                 newkey = String ();
1078                 newkey.push_back (ch);
1079
1080                 if (m_factory->m_table.is_defined_key (newkey)) {
1081                     ++m_inputing_key;
1082                     m_inputing_caret = 1;
1083                     m_inputted_keys.insert (m_inputted_keys.begin () + m_inputing_key, newkey);
1084                     insert_ok = true;
1085                 }
1086             } else if (m_inputing_caret == 0) {
1087                 newkey = String ();
1088                 newkey.push_back (ch);
1089
1090                 if (m_factory->m_table.is_defined_key (newkey)) {
1091                     m_inputing_caret = 1;
1092                     m_inputted_keys.insert (m_inputted_keys.begin () + m_inputing_key, newkey);
1093                     insert_ok = true;
1094                 }
1095             }
1096         } else if (!m_factory->m_table.is_multi_wildcard_char (ch)) {
1097             newkey = String ();
1098             newkey.push_back (ch);
1099
1100             if (m_factory->m_table.is_defined_key (newkey)) {
1101                 m_inputted_keys.push_back (newkey);
1102                 m_inputing_key = 0;
1103                 m_inputing_caret = 1; 
1104                 insert_ok = true;
1105             }
1106         }
1107     }
1108
1109     if (insert_ok) {
1110         //Do some extra work in normal mode.
1111         if (m_add_phrase_mode != 1) {
1112             //auto select
1113             if (m_factory->m_table.is_auto_select () &&
1114                 m_converted_strings.size () == old_inputing_key &&
1115                 old_inputing_key + 1 == m_inputing_key &&
1116                 m_lookup_table.number_of_candidates () &&
1117                 m_inputted_keys [m_inputing_key].length ()) {
1118                 lookup_to_converted (m_lookup_table.get_cursor_pos ());
1119             }
1120
1121             //discard invalid key
1122             if (m_factory->m_table.is_discard_invalid_key () &&
1123                 m_converted_strings.size () == old_inputing_key &&
1124                 old_inputing_key + 1 == m_inputing_key &&
1125                 m_lookup_table.number_of_candidates () == 0 &&
1126                 m_inputted_keys [m_inputing_key].length ()) {
1127                 m_inputted_keys.erase (m_inputted_keys.begin () + old_inputing_key);
1128                 m_inputing_key --;
1129             }
1130
1131             if (m_converted_strings.size () == m_inputing_key) {
1132                 refresh_lookup_table (false, true);
1133
1134                 // If auto commit is true, then do auto select when
1135                 // there is only one candidate for this key.
1136                 if (m_lookup_table.number_of_candidates () == 1 &&
1137                     m_factory->m_table.is_auto_commit () &&
1138                     !m_factory->m_table.is_defined_key (
1139                         m_inputted_keys [m_inputing_key],
1140                         GT_SEARCH_ONLY_LONGER)) {
1141                     lookup_to_converted (m_lookup_table.get_cursor_pos ());
1142                     refresh_lookup_table ();
1143                 } else {
1144                     refresh_lookup_table (true, false);
1145                 }
1146             }
1147
1148             if (m_inputted_keys.size () > SCIM_TABLE_MAX_INPUTTED_KEYS ||
1149                 m_factory->m_table.is_auto_commit ())
1150                 commit_converted ();
1151
1152             // If it's a key end char, then append an empty key.
1153             if (m_factory->m_table.is_key_end_char (ch) &&
1154                 m_inputing_key == m_inputted_keys.size () -1 &&
1155                 m_inputted_keys [m_inputing_key].length () &&
1156                 m_inputing_caret == m_inputted_keys [m_inputing_key].length ()) {
1157                 ++m_inputing_key;
1158                 m_inputing_caret = 0;
1159                 m_inputted_keys.insert (m_inputted_keys.begin () + m_inputing_key, String ());
1160             }
1161         }
1162
1163         refresh_preedit ();
1164         refresh_aux_string ();
1165
1166         return true;
1167     }
1168
1169     return false;
1170 }
1171
1172 bool
1173 TableInstance::erase (bool backspace)
1174 {
1175     if (m_inputted_keys.size ()) {
1176         if (backspace && (m_inputing_key > 0 || m_inputing_caret > 0)) {
1177             if (m_inputing_caret > 0) {
1178                 --m_inputing_caret;
1179                 m_inputted_keys [m_inputing_key].erase (m_inputing_caret, 1);
1180             } else {
1181                 if (m_inputted_keys [m_inputing_key].length () == 0)
1182                     m_inputted_keys.erase (m_inputted_keys.begin () + m_inputing_key);
1183
1184                 --m_inputing_key;
1185                 m_inputing_caret = m_inputted_keys [m_inputing_key].length ();
1186
1187                 if (m_inputing_caret > 0) {
1188                     --m_inputing_caret;
1189                     m_inputted_keys [m_inputing_key].erase (m_inputing_caret, 1);
1190                 }
1191             }
1192
1193             if (m_inputted_keys [m_inputing_key].length () == 0) {
1194                 m_inputted_keys.erase (m_inputted_keys.begin () + m_inputing_key);
1195
1196                 if (m_inputing_key > 0) {
1197                     --m_inputing_key;
1198                     m_inputing_caret = m_inputted_keys [m_inputing_key].length ();
1199                 }
1200             }
1201         } else if (!backspace) {
1202             if (m_inputing_caret < m_inputted_keys [m_inputing_key].length ()) {
1203                 m_inputted_keys [m_inputing_key].erase (m_inputing_caret, 1);
1204             }
1205             if (m_inputted_keys [m_inputing_key].length () == 0) {
1206                 m_inputted_keys.erase (m_inputted_keys.begin () + m_inputing_key);
1207             }
1208             if (m_inputing_key == m_inputted_keys.size () && m_inputing_key > 0) {
1209                 --m_inputing_key;
1210                 m_inputing_caret = m_inputted_keys [m_inputing_key].length ();
1211             }
1212         } else {
1213             return true;
1214         }
1215
1216         if (m_inputted_keys.size () == 1 && m_inputted_keys [0].length () == 0) {
1217             m_inputted_keys.clear ();
1218             m_inputing_key = 0;
1219             m_inputing_caret = 0;
1220         }
1221
1222         if (m_add_phrase_mode != 1) {
1223             if (m_converted_strings.size () > m_inputing_key) {
1224                 m_converted_strings.erase (m_converted_strings.begin () + m_inputing_key, m_converted_strings.end ());
1225                 m_converted_indexes.erase (m_converted_indexes.begin () + m_inputing_key, m_converted_indexes.end ());
1226             }
1227             refresh_lookup_table ();
1228         }
1229
1230         refresh_preedit ();
1231         refresh_aux_string ();
1232         return true;
1233     }
1234     return false;
1235 }
1236
1237 bool
1238 TableInstance::space_hit ()
1239 {
1240     if (m_inputted_keys.size ()) {
1241         if (m_add_phrase_mode == 1) {
1242             if (m_factory->m_table.add_phrase (m_inputted_keys [0], m_last_committed)) {
1243                 m_add_phrase_mode = 2;
1244                 m_factory->refresh (true);
1245             } else {
1246                 m_add_phrase_mode = 3;
1247             }
1248
1249             m_inputted_keys.clear ();
1250             m_last_committed = WideString ();
1251             m_inputing_caret = m_inputing_key = 0;
1252         } else {
1253             if (m_converted_strings.size () == 0 && m_lookup_table.number_of_candidates () == 0)
1254                 return true;
1255
1256             if (m_lookup_table.number_of_candidates () && m_converted_strings.size () < m_inputted_keys.size ()) {
1257                 lookup_to_converted (m_lookup_table.get_cursor_pos ());
1258                 refresh_lookup_table ();
1259             }
1260
1261             if (m_converted_strings.size () == m_inputted_keys.size () ||
1262                 (m_converted_strings.size () == m_inputted_keys.size () - 1 &&
1263                  m_inputted_keys [m_inputing_key].length () == 0))
1264                 commit_converted ();
1265         }
1266
1267         refresh_preedit ();
1268         refresh_aux_string ();
1269
1270         return true;
1271     }
1272     return false;
1273 }
1274
1275 bool
1276 TableInstance::enter_hit ()
1277 {
1278     if (m_inputted_keys.size ()) {
1279         if (m_add_phrase_mode == 1) {
1280             if (m_factory->m_table.add_phrase (m_inputted_keys [0], m_last_committed)) {
1281                 m_add_phrase_mode = 2;
1282                 m_factory->refresh (true);
1283             } else {
1284                 m_add_phrase_mode = 3;
1285             }
1286
1287             m_inputted_keys.clear ();
1288             m_last_committed = WideString ();
1289             m_inputing_caret = m_inputing_key = 0;
1290
1291             refresh_preedit ();
1292             refresh_aux_string ();
1293         } else {
1294             reset ();
1295         }
1296         return true;
1297     }
1298
1299     m_last_committed = WideString ();
1300
1301     return false;
1302 }
1303
1304 bool
1305 TableInstance::lookup_cursor_up ()
1306 {
1307     if (m_inputted_keys.size () && m_lookup_table.number_of_candidates ()) {
1308         m_lookup_table.cursor_up ();
1309         refresh_lookup_table (true, false);
1310         refresh_preedit ();
1311         refresh_aux_string ();
1312         return true;
1313     }
1314     return false;
1315 }
1316
1317 bool
1318 TableInstance::lookup_cursor_down ()
1319 {
1320     if (m_inputted_keys.size () && m_lookup_table.number_of_candidates ()) {
1321         m_lookup_table.cursor_down ();
1322         refresh_lookup_table (true, false);
1323         refresh_preedit ();
1324         refresh_aux_string ();
1325         return true;
1326     }
1327     return false;
1328 }
1329
1330 bool
1331 TableInstance::lookup_cursor_up_to_longer ()
1332 {
1333     if (m_inputted_keys.size () && m_lookup_table.number_of_candidates ()) {
1334         //Get current lookup table cursor
1335         uint32 cursor = m_lookup_table.get_cursor_pos ();
1336         //Get current phrase length
1337         uint32 curlen = m_factory->m_table.get_phrase_length (m_lookup_table_indexes [cursor]);
1338
1339         do {
1340             m_lookup_table.cursor_up ();
1341             cursor = m_lookup_table.get_cursor_pos ();
1342             if (curlen < m_factory->m_table.get_phrase_length (m_lookup_table_indexes [cursor]))
1343                 break;
1344         } while (cursor);
1345
1346         refresh_lookup_table (true, false);
1347         refresh_preedit ();
1348         refresh_aux_string ();
1349         return true;
1350     }
1351     return false;
1352 }
1353
1354 bool
1355 TableInstance::lookup_cursor_down_to_shorter ()
1356 {
1357     if (m_inputted_keys.size () && m_lookup_table.number_of_candidates ()) {
1358         uint32 entries = m_lookup_table.number_of_candidates ();
1359         //Get current lookup table cursor
1360         uint32 cursor = m_lookup_table.get_cursor_pos ();
1361         //Get current phrase length
1362         uint32 curlen = m_factory->m_table.get_phrase_length (m_lookup_table_indexes [cursor]);
1363
1364         do {
1365             m_lookup_table.cursor_down ();
1366             cursor = m_lookup_table.get_cursor_pos ();
1367             if (curlen > m_factory->m_table.get_phrase_length (m_lookup_table_indexes [cursor]))
1368                 break;
1369         } while (cursor < entries - 1);
1370
1371         refresh_lookup_table (true, false);
1372         refresh_preedit ();
1373         refresh_aux_string ();
1374         return true;
1375     }
1376     return false;
1377 }
1378
1379 bool
1380 TableInstance::lookup_page_up ()
1381 {
1382     if (m_inputted_keys.size () &&
1383          m_lookup_table.get_current_page_size () <
1384          m_lookup_table.number_of_candidates ()) {
1385
1386         m_lookup_table.page_up ();
1387         refresh_lookup_table (true, false);
1388         refresh_preedit ();
1389         refresh_aux_string ();
1390         return true;
1391     }
1392     return false;
1393 }
1394
1395 bool
1396 TableInstance::lookup_page_down ()
1397 {
1398     if (m_inputted_keys.size () && 
1399          m_lookup_table.get_current_page_size () <
1400          m_lookup_table.number_of_candidates ()) {
1401
1402         if (!m_lookup_table.page_down ())
1403             while (m_lookup_table.page_up ()) NULL;
1404
1405         refresh_lookup_table (true, false);
1406         refresh_preedit ();
1407         refresh_aux_string ();
1408         return true;
1409     }
1410     return false;
1411 }
1412
1413 bool
1414 TableInstance::lookup_select (int index)
1415 {
1416     if (m_inputted_keys.size ()) {
1417         if (m_lookup_table.number_of_candidates () == 0)
1418             return true;
1419
1420         index += m_lookup_table.get_current_page_start ();
1421
1422         lookup_to_converted (index);
1423
1424         if (m_converted_strings.size () == m_inputted_keys.size () ||
1425             (m_converted_strings.size () == m_inputted_keys.size () - 1 &&
1426              m_inputted_keys [m_inputing_key].length () == 0))
1427             commit_converted ();
1428
1429         refresh_lookup_table ();
1430         refresh_preedit ();
1431         refresh_aux_string ();
1432
1433         return true;
1434     }
1435
1436     return false;
1437 }
1438
1439 bool
1440 TableInstance::post_process (char key)
1441 {
1442     // Auto select and commit the candidate item when an invalid key is pressed.
1443     if (m_factory->m_table.is_auto_commit () &&
1444         m_converted_strings.size () == m_inputing_key &&
1445         m_inputing_key + 1 == m_inputted_keys.size () &&
1446         m_inputing_caret == m_inputted_keys [m_inputing_key].length () &&
1447         m_lookup_table.number_of_candidates ()) {
1448
1449         lookup_to_converted (m_lookup_table.get_cursor_pos ());
1450         commit_converted ();
1451
1452         refresh_lookup_table ();
1453         refresh_preedit ();
1454         refresh_aux_string ();
1455     }
1456
1457     if (m_inputted_keys.size ()) return true;
1458
1459     if ((ispunct (key) && m_full_width_punct [m_forward?1:0]) ||
1460         ((isalnum (key) || key == 0x20) && m_full_width_letter [m_forward?1:0])) {
1461         WideString str;
1462         if (key == '.')
1463             str.push_back (0x3002);
1464         else if (key == '\\')
1465             str.push_back (0x3001);
1466         else if (key == '^') {
1467             str.push_back (0x2026);
1468             str.push_back (0x2026);
1469         } else if (key == '\"') {
1470             if (!m_double_quotation_state)
1471                 str.push_back (0x201c);
1472             else
1473                 str.push_back (0x201d);
1474             m_double_quotation_state = !m_double_quotation_state;
1475         } else if (key == '\'') {
1476             if (!m_single_quotation_state)
1477                 str.push_back (0x2018);
1478             else
1479                 str.push_back (0x2019);
1480             m_single_quotation_state = !m_single_quotation_state;
1481         } else {
1482             str.push_back (scim_wchar_to_full_width (key));
1483         }
1484
1485         commit_string (str);
1486
1487         m_last_committed = WideString ();
1488
1489         return true;
1490     }
1491
1492     return false;
1493 }
1494
1495 bool
1496 TableInstance::delete_phrase ()
1497 {
1498     if (m_lookup_table.number_of_candidates ()) {
1499         int pos       = m_lookup_table.get_cursor_pos ();
1500         uint32 offset = m_lookup_table_indexes [pos];
1501
1502         if (m_factory->m_table.delete_phrase (offset)) {
1503             m_factory->refresh (true);
1504             refresh_lookup_table ();
1505         }
1506         return true;
1507     }
1508     return false;
1509 }
1510
1511 void
1512 TableInstance::lookup_to_converted (int index)
1513 {
1514     if (index < 0 || index >= m_lookup_table.number_of_candidates ())
1515         return;
1516
1517     uint32 offset  = m_lookup_table_indexes [index];
1518     WideString str = m_factory->m_table.get_phrase (offset);
1519
1520     m_converted_strings.push_back (str);
1521     m_converted_indexes.push_back (offset);
1522
1523     if (m_inputing_key < m_converted_strings.size ()) {
1524         m_inputing_key = m_converted_strings.size ();
1525         if (m_inputing_key >= m_inputted_keys.size ())
1526             m_inputted_keys.push_back (String (""));
1527         m_inputing_caret = 0;
1528     }
1529 }
1530
1531 void
1532 TableInstance::commit_converted ()
1533 {
1534     if (m_converted_strings.size ()) {
1535         WideString res;
1536
1537         for (size_t i=0; i<m_converted_strings.size (); ++i)
1538             res += m_converted_strings [i];
1539
1540         // Hide preedit string before committing string,
1541         // to prevent some buggy clients from inserting the string into wrong place.
1542         // Preedit string will be refreshed after return from commit_converted ().
1543         hide_preedit_string ();
1544         commit_string (res);
1545
1546         if (utf8_wcstombs (m_last_committed).length () >= 255)
1547             m_last_committed = WideString ();
1548
1549         m_last_committed += res;
1550
1551         m_inputted_keys.erase (m_inputted_keys.begin (), m_inputted_keys.begin () + m_converted_strings.size ());
1552         m_inputing_key -= m_converted_strings.size ();
1553
1554         if (m_inputted_keys.size () == 1 && m_inputted_keys [0].length () == 0) {
1555             m_inputted_keys.clear ();
1556             m_inputing_key = 0;
1557             m_inputing_caret = 0;
1558         }
1559
1560         if (m_inputted_keys.size ()) {
1561             m_inputing_key = m_inputted_keys.size () - 1;
1562             m_inputing_caret = m_inputted_keys [m_inputing_key].length ();
1563         }
1564
1565         if (m_factory->m_table.is_dynamic_adjust ()){
1566             for (size_t i = 0; i < m_converted_indexes.size (); ++i) {
1567                 uint32 freq = m_factory->m_table.get_phrase_frequency (m_converted_indexes [i]);
1568                 if (freq < SCIM_GT_MAX_PHRASE_FREQ) {
1569                     uint32 delta = ((SCIM_GT_MAX_PHRASE_FREQ - freq) >> SCIM_GT_PHRASE_FREQ_DELTA_SHIFT);
1570                     freq += (delta ? delta : 1);
1571                     m_factory->m_table.set_phrase_frequency (m_converted_indexes [i], freq);
1572                 }
1573             }
1574             m_factory->refresh (false);
1575         }
1576
1577         m_converted_strings.clear ();
1578         m_converted_indexes.clear ();
1579     }
1580 }
1581
1582 void
1583 TableInstance::refresh_preedit ()
1584 {
1585     WideString preedit_string;
1586     int start = 0;
1587     int length = 0;
1588     int caret = 0;
1589     int end = 0;
1590     size_t i;
1591
1592     if (m_inputted_keys.size () == 0) {
1593         hide_preedit_string ();
1594         return;
1595     }
1596  
1597     for (i = 0; i<m_converted_strings.size (); ++i)
1598         preedit_string += m_converted_strings [i];
1599
1600     int inputted_keys = m_inputted_keys.size ();
1601
1602     if (m_inputted_keys [inputted_keys - 1].length () == 0)
1603         --inputted_keys;
1604
1605     // Fill the preedit string.
1606     if (m_factory->m_table.is_auto_fill () &&
1607         m_converted_strings.size () == inputted_keys - 1 &&
1608         m_inputing_caret == m_inputted_keys [m_inputing_key].length () &&
1609         m_lookup_table.number_of_candidates ()) {
1610
1611         uint32 offset = m_lookup_table_indexes [m_lookup_table.get_cursor_pos ()];
1612         WideString str = m_factory->m_table.get_phrase (offset);
1613
1614         start = preedit_string.length ();
1615         preedit_string += str;
1616         length = str.length ();
1617         caret = preedit_string.length ();
1618     } else {
1619         i = m_converted_strings.size ();
1620         caret = start = preedit_string.length ();
1621
1622         for (i = m_converted_strings.size (); i < inputted_keys; ++i) {
1623             if (m_factory->m_table.is_show_key_prompt ()) {
1624                 preedit_string += m_factory->m_table.get_key_prompt (m_inputted_keys [i]);
1625                 if (i == m_inputing_key)
1626                     caret += (m_factory->m_table.get_key_prompt (m_inputted_keys [i].substr (0, m_inputing_caret))).length ();
1627             } else {
1628                 preedit_string += utf8_mbstowcs (m_inputted_keys [i]);
1629                 if (i == m_inputing_key)
1630                     caret += m_inputing_caret;
1631             }
1632
1633             if (i == m_converted_strings.size ())
1634                 length = preedit_string.length () - start;
1635
1636             if (i < inputted_keys - 1)
1637                 preedit_string.push_back ((ucs4_t)' ');
1638
1639             if (i < m_inputing_key)
1640                 caret = preedit_string.length ();
1641         }
1642     }
1643     m_preedit_string = preedit_string;
1644     if (preedit_string.length () == 0) {
1645         hide_preedit_string ();
1646         return;
1647     }
1648
1649     AttributeList attrs;
1650
1651     if (length)
1652     {
1653         if (start)
1654             attrs.push_back (Attribute(0, start, SCIM_ATTR_DECORATE, SCIM_ATTR_DECORATE_UNDERLINE));
1655         attrs.push_back (Attribute(start, length, SCIM_ATTR_DECORATE, SCIM_ATTR_DECORATE_HIGHLIGHT));
1656         end = start+length;
1657         if (end < preedit_string.length())
1658             attrs.push_back (Attribute(end, preedit_string.length()- end, SCIM_ATTR_DECORATE, SCIM_ATTR_DECORATE_UNDERLINE));
1659     }
1660     update_preedit_string (preedit_string, attrs);
1661     update_preedit_caret (caret);
1662
1663     show_preedit_string ();
1664 }
1665
1666 void
1667 TableInstance::refresh_lookup_table (bool show, bool refresh)
1668 {
1669     m_lookup_table.set_page_size (m_factory->m_table.get_select_keys ().size ());
1670
1671     if (refresh) {
1672         std::vector <uint32> phrases;
1673         WideString str;
1674
1675         m_lookup_table.clear ();
1676         m_lookup_table_indexes.clear ();
1677
1678         if (m_converted_strings.size () < m_inputted_keys.size ()) {
1679
1680             String key = m_inputted_keys [m_converted_strings.size ()];
1681
1682             if (key.length () &&
1683                 m_factory->m_table.find (phrases,
1684                                          key,
1685                                          m_factory->m_user_phrase_first,
1686                                          m_factory->m_long_phrase_first)) {
1687
1688                 bool show_full_hint = m_factory->m_table.is_wildcard_key (key);
1689                 std::set<WideString> candiadtes;
1690                 for (size_t i = 0; i < phrases.size (); ++i) {
1691                     str = m_factory->m_table.get_phrase (phrases [i]);
1692
1693                     if (m_iconv.test_convert (str)) {
1694                         if (m_factory->m_show_key_hint) {
1695                             String hint = m_factory->m_table.get_key (phrases [i]);
1696
1697                             if (show_full_hint)
1698                                 str += utf8_mbstowcs (hint);
1699                             else if (hint.length () > key.length ())
1700                                 str += utf8_mbstowcs (hint.substr (key.length ()));
1701                         }
1702 #if 0
1703                         AttributeList attrs;
1704
1705                         if (m_factory->m_table.is_user_phrase (phrases [i]))
1706                             attrs.push_back (Attribute (0, str.length (), SCIM_ATTR_FOREGROUND, SCIM_RGB_COLOR(32, 32, 255)));
1707
1708                         m_lookup_table.append_candidate (str, attrs);
1709 #endif
1710                         if (candiadtes.find (str) != candiadtes.end())
1711                             continue;
1712                         candiadtes.insert (str);
1713                         m_lookup_table.append_candidate (str);
1714                         m_lookup_table_indexes.push_back (phrases [i]);
1715                     }
1716                 }
1717             }
1718         }
1719     }
1720     if (show) {
1721         if (m_lookup_table.number_of_candidates () &&
1722             (m_factory->m_table.is_always_show_lookup () ||
1723              m_inputing_key < m_inputted_keys.size () - 1 ||
1724              m_inputing_caret < m_inputted_keys [m_inputing_key].length () ||
1725              m_converted_strings.size () < m_inputted_keys.size () - 1)) {
1726             update_lookup_table (m_lookup_table);
1727         } else {        
1728             if (m_inputted_keys.size () &&
1729                 (m_inputing_caret || m_lookup_table.number_of_candidates ()))
1730             {
1731                 m_lookup_table.clear ();
1732                 update_lookup_table (m_lookup_table);
1733             }
1734             else
1735                 update_lookup_table (m_common_lookup_table);
1736         }
1737     }
1738 }
1739
1740 void
1741 TableInstance::refresh_aux_string ()
1742 {
1743     WideString    prompt;
1744     AttributeList attributes;
1745
1746     if (m_add_phrase_mode == 1) {
1747         prompt = utf8_mbstowcs (_("Input a key string for phrase: ")) + m_last_committed;
1748     } else if (m_add_phrase_mode == 2) {
1749         prompt = utf8_mbstowcs (_("Success."));
1750         attributes.push_back (Attribute (0, prompt.length (), SCIM_ATTR_FOREGROUND, SCIM_RGB_COLOR(32, 255, 32)));
1751     } else if (m_add_phrase_mode == 3) {
1752         prompt = utf8_mbstowcs (_("Failed."));
1753         attributes.push_back (Attribute (0, prompt.length (), SCIM_ATTR_FOREGROUND, SCIM_RGB_COLOR(255, 32, 32)));
1754     } else {
1755         if (!m_factory->m_show_prompt || m_inputted_keys.size () == 0) {
1756             hide_aux_string ();
1757             return;
1758         }
1759
1760         if (!m_factory->m_table.is_show_key_prompt ())
1761             prompt = m_factory->m_table.get_key_prompt (m_inputted_keys [m_inputing_key]);
1762
1763         if (m_lookup_table.number_of_candidates () && ! m_factory->m_show_key_hint) {
1764             prompt += utf8_mbstowcs (" <");
1765             unsigned int att_start = prompt.length ();
1766
1767             if (m_factory->m_table.is_show_key_prompt ())
1768                 prompt += m_factory->m_table.get_key_prompt (m_factory->m_table.get_key (
1769                             m_lookup_table_indexes [m_lookup_table.get_cursor_pos ()]));
1770             else
1771                 prompt += utf8_mbstowcs (m_factory->m_table.get_key (
1772                             m_lookup_table_indexes [m_lookup_table.get_cursor_pos ()]));
1773
1774             unsigned int att_length = prompt.length () - att_start;
1775             prompt += utf8_mbstowcs (">");
1776             attributes.push_back (Attribute (att_start, att_length, SCIM_ATTR_FOREGROUND, SCIM_RGB_COLOR(128, 128, 255)));
1777         }
1778     }
1779
1780     if (prompt.length ()) {
1781         update_aux_string (prompt, attributes);
1782         show_aux_string ();
1783     } else {
1784         hide_aux_string ();
1785     }
1786 }
1787
1788 bool
1789 TableInstance::match_key_event (const std::vector<KeyEvent>& keyvec,
1790                                       const KeyEvent& key)
1791 {
1792     std::vector<KeyEvent>::const_iterator kit; 
1793
1794     for (kit = keyvec.begin (); kit != keyvec.end (); ++kit) {
1795         if (key.code == kit->code && key.mask == kit->mask)
1796             if (!(key.mask & SCIM_KEY_ReleaseMask) || m_prev_key.code == key.code)
1797                 return true;
1798     }
1799     return false;
1800 }
1801 /*
1802 vi:ts=4:nowrap:ai:expandtab
1803 */