Add show_lookup_table in reset
[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         show_lookup_table ();
793     } else {
794         hide_lookup_table();
795     }
796     hide_preedit_string ();
797     hide_aux_string ();
798 }
799
800 void
801 TableInstance::focus_in ()
802 {
803     m_focused = true;
804
805     if (m_add_phrase_mode != 1) {
806         m_last_committed = WideString ();
807         m_add_phrase_mode = 0;
808     }
809
810     //refresh_lookup_table (true, false);
811     refresh_preedit ();
812     refresh_aux_string ();
813     initialize_properties ();
814 }
815
816 void
817 TableInstance::focus_out ()
818 {
819     m_focused = false;
820     reset ();
821 }
822
823 void
824 TableInstance::trigger_property (const String &property)
825 {
826     if (property == SCIM_PROP_STATUS) {
827         m_forward = !m_forward;
828         refresh_status_property ();
829         refresh_letter_property ();
830         refresh_punct_property ();
831         reset ();
832     } else if (property == SCIM_PROP_LETTER && m_factory->m_table.is_use_full_width_letter ()) {
833         m_full_width_letter [m_forward?1:0] =
834             !m_full_width_letter [m_forward?1:0];
835         refresh_letter_property ();
836     } else if (property == SCIM_PROP_PUNCT && m_factory->m_table.is_use_full_width_punct ()) {
837         m_full_width_punct [m_forward?1:0] = 
838             !m_full_width_punct [m_forward?1:0];
839         refresh_punct_property ();
840     }
841 }
842  
843 void
844 TableInstance::set_layout (unsigned int layout)
845 {
846     switch (layout)
847     {
848         case ECORE_IMF_INPUT_PANEL_LAYOUT_NORMAL:
849         case ECORE_IMF_INPUT_PANEL_LAYOUT_NUMBER:
850         case ECORE_IMF_INPUT_PANEL_LAYOUT_EMAIL:
851         case ECORE_IMF_INPUT_PANEL_LAYOUT_URL:
852             refresh_lookup_table(true,false);
853             show_lookup_table ();
854             m_forward = false;
855             break;
856         default:
857             hide_lookup_table ();
858             m_forward = true;
859     }
860 }
861
862 void
863 TableInstance::initialize_properties ()
864 {
865     PropertyList proplist;
866
867     proplist.push_back (m_factory->m_status_property);
868
869     if (m_factory->m_table.is_use_full_width_letter ())
870         proplist.push_back (m_factory->m_letter_property);
871
872     if (m_factory->m_table.is_use_full_width_punct ())
873         proplist.push_back (m_factory->m_punct_property);
874
875     register_properties (proplist);
876
877     refresh_status_property ();
878     refresh_letter_property ();
879     refresh_punct_property ();
880 }
881
882 void
883 TableInstance::refresh_status_property ()
884 {
885     if (m_focused) {
886         if (m_forward)
887             m_factory->m_status_property.set_label (_("En"));
888         else
889             m_factory->m_status_property.set_label (utf8_wcstombs (m_factory->m_table.get_status_prompt ()));
890
891         update_property (m_factory->m_status_property);
892     }
893 }
894
895 void
896 TableInstance::refresh_letter_property ()
897 {
898     if (m_focused && m_factory->m_table.is_use_full_width_letter ()) {
899         m_factory->m_letter_property.set_icon (
900             m_full_width_letter [m_forward?1:0] ? SCIM_FULL_LETTER_ICON : SCIM_HALF_LETTER_ICON);
901         update_property (m_factory->m_letter_property);
902     }
903 }
904
905 void
906 TableInstance::refresh_punct_property ()
907 {
908     if (m_focused && m_factory->m_table.is_use_full_width_punct ()) {
909         m_factory->m_punct_property.set_icon (
910             m_full_width_punct [m_forward?1:0] ? SCIM_FULL_PUNCT_ICON : SCIM_HALF_PUNCT_ICON);
911         update_property (m_factory->m_punct_property);
912     }
913 }
914
915 bool
916 TableInstance::caret_left ()
917 {
918     if (m_inputted_keys.size ()) {
919         if (m_inputing_caret > 0) {
920             --m_inputing_caret;
921             refresh_lookup_table (true, false);
922         } else if (m_inputing_key > 0) {
923             --m_inputing_key;
924             m_inputing_caret = m_inputted_keys [m_inputing_key].length ();
925
926             if (m_converted_strings.size () > m_inputing_key) {
927                 m_converted_strings.pop_back ();
928                 m_converted_indexes.pop_back ();
929                 refresh_lookup_table ();
930             } else {
931                 refresh_lookup_table (true, false);
932             }
933         } else {
934             return caret_end ();
935         }
936
937         refresh_preedit ();
938         refresh_aux_string ();
939         return true;
940     }
941     return false;
942 }
943
944 bool
945 TableInstance::caret_right ()
946 {
947     if (m_inputted_keys.size ()) {
948         if (m_inputing_caret < m_inputted_keys [m_inputing_key].size ()) {
949             ++m_inputing_caret;
950         } else if (m_inputing_key < m_inputted_keys.size () - 1) {
951             ++m_inputing_key;
952             m_inputing_caret = 0;
953         } else {
954             return caret_home ();
955         }
956         refresh_lookup_table (true, false);
957         refresh_preedit ();
958         refresh_aux_string ();
959         return true;
960     }
961     return false;
962 }
963
964 bool
965 TableInstance::caret_home ()
966 {
967     if (m_inputted_keys.size ()) {
968         m_inputing_key = 0;
969         m_inputing_caret = 0;
970
971         if (m_converted_strings.size ()) {
972             m_converted_strings.clear ();
973             m_converted_indexes.clear ();
974             refresh_lookup_table ();
975         } else {
976             refresh_lookup_table (true, false);
977         }
978
979         refresh_preedit ();
980         refresh_aux_string ();
981         return true;
982     }
983     return false;
984 }
985
986 bool
987 TableInstance::caret_end ()
988 {
989     if (m_inputted_keys.size ()) {
990         m_inputing_key = m_inputted_keys.size () - 1;
991         m_inputing_caret = m_inputted_keys [m_inputing_key].length ();
992
993         refresh_lookup_table (true, false);
994         refresh_preedit ();
995         refresh_aux_string ();
996         return true;
997     }
998     return false;
999 }
1000
1001 bool
1002 TableInstance::test_insert (char key)
1003 {
1004     if (m_factory->m_table.is_valid_char (key)) {
1005         String newkey;
1006         if (m_inputted_keys.size ()) {
1007             newkey = m_inputted_keys [m_inputing_key];
1008             newkey.insert (newkey.begin () + m_inputing_caret, key);
1009         } else {
1010             newkey.push_back (key);
1011         }
1012
1013         return m_factory->m_table.is_defined_key (newkey);
1014     }
1015     return false;
1016 }
1017
1018 bool
1019 TableInstance::insert (char ch)
1020 {
1021     if (!ch) return false;
1022
1023     String newkey;
1024     uint32 old_inputing_key = m_inputing_key;
1025     bool insert_ok = false;
1026
1027     if (m_inputted_keys.size () - m_converted_strings.size () >
1028         SCIM_TABLE_MAX_INPUTTED_KEYS)
1029         return false;
1030
1031     // If current inputing key is empty, then the last inputing key is the previous key.
1032     if (m_inputted_keys.size () && m_inputing_key && !m_inputted_keys [m_inputing_key].length ())
1033         -- old_inputing_key;
1034
1035     if (m_factory->m_table.is_split_char (ch)) {
1036         // split char is invalid during add phrase mode.
1037         if (m_add_phrase_mode == 1)
1038             return true;
1039         else if (m_inputted_keys.size () == 0)
1040             return false;
1041         else if (m_inputing_key == m_inputted_keys.size () -1 &&
1042                 m_inputted_keys [m_inputing_key].length () &&
1043                 m_inputing_caret == m_inputted_keys [m_inputing_key].length ()) {
1044             ++m_inputing_key;
1045             m_inputing_caret = 0;
1046             m_inputted_keys.insert (m_inputted_keys.begin () + m_inputing_key, String ());
1047         } else {
1048             return false;
1049         }
1050
1051         insert_ok = true;
1052     } else if (m_factory->m_table.is_valid_char (ch)) {
1053         if (m_add_phrase_mode == 1) {
1054             m_inputing_key = 0;
1055             if (!m_inputted_keys.size ()) {
1056                 m_inputted_keys.push_back (String (""));
1057                 m_inputing_caret = 0;
1058             } else if (m_inputted_keys [0].length () >= m_factory->m_table.get_max_key_length ()) {
1059                 return true;
1060             }
1061
1062             m_inputted_keys [0].insert (m_inputted_keys [0].begin () + m_inputing_caret, ch);
1063             ++m_inputing_caret;
1064             insert_ok = true;
1065         } else if (m_inputted_keys.size ()) {
1066             newkey = m_inputted_keys [m_inputing_key];
1067             newkey.insert (newkey.begin () + m_inputing_caret, ch);
1068
1069             if ((m_factory->m_table.is_auto_split () == false ||
1070                  m_factory->m_table.is_defined_key (newkey)) &&
1071                 newkey.length () <= m_factory->m_table.get_max_key_length ()) {
1072                 m_inputted_keys [m_inputing_key] = newkey;
1073                 ++m_inputing_caret;
1074                 insert_ok = true;
1075             } else if (m_inputing_caret == m_inputted_keys [m_inputing_key].length ()) {
1076                 newkey = String ();
1077                 newkey.push_back (ch);
1078
1079                 if (m_factory->m_table.is_defined_key (newkey)) {
1080                     ++m_inputing_key;
1081                     m_inputing_caret = 1;
1082                     m_inputted_keys.insert (m_inputted_keys.begin () + m_inputing_key, newkey);
1083                     insert_ok = true;
1084                 }
1085             } else if (m_inputing_caret == 0) {
1086                 newkey = String ();
1087                 newkey.push_back (ch);
1088
1089                 if (m_factory->m_table.is_defined_key (newkey)) {
1090                     m_inputing_caret = 1;
1091                     m_inputted_keys.insert (m_inputted_keys.begin () + m_inputing_key, newkey);
1092                     insert_ok = true;
1093                 }
1094             }
1095         } else if (!m_factory->m_table.is_multi_wildcard_char (ch)) {
1096             newkey = String ();
1097             newkey.push_back (ch);
1098
1099             if (m_factory->m_table.is_defined_key (newkey)) {
1100                 m_inputted_keys.push_back (newkey);
1101                 m_inputing_key = 0;
1102                 m_inputing_caret = 1; 
1103                 insert_ok = true;
1104             }
1105         }
1106     }
1107
1108     if (insert_ok) {
1109         //Do some extra work in normal mode.
1110         if (m_add_phrase_mode != 1) {
1111             //auto select
1112             if (m_factory->m_table.is_auto_select () &&
1113                 m_converted_strings.size () == old_inputing_key &&
1114                 old_inputing_key + 1 == m_inputing_key &&
1115                 m_lookup_table.number_of_candidates () &&
1116                 m_inputted_keys [m_inputing_key].length ()) {
1117                 lookup_to_converted (m_lookup_table.get_cursor_pos ());
1118             }
1119
1120             //discard invalid key
1121             if (m_factory->m_table.is_discard_invalid_key () &&
1122                 m_converted_strings.size () == old_inputing_key &&
1123                 old_inputing_key + 1 == m_inputing_key &&
1124                 m_lookup_table.number_of_candidates () == 0 &&
1125                 m_inputted_keys [m_inputing_key].length ()) {
1126                 m_inputted_keys.erase (m_inputted_keys.begin () + old_inputing_key);
1127                 m_inputing_key --;
1128             }
1129
1130             if (m_converted_strings.size () == m_inputing_key) {
1131                 refresh_lookup_table (false, true);
1132
1133                 // If auto commit is true, then do auto select when
1134                 // there is only one candidate for this key.
1135                 if (m_lookup_table.number_of_candidates () == 1 &&
1136                     m_factory->m_table.is_auto_commit () &&
1137                     !m_factory->m_table.is_defined_key (
1138                         m_inputted_keys [m_inputing_key],
1139                         GT_SEARCH_ONLY_LONGER)) {
1140                     lookup_to_converted (m_lookup_table.get_cursor_pos ());
1141                     refresh_lookup_table ();
1142                 } else {
1143                     refresh_lookup_table (true, false);
1144                 }
1145             }
1146
1147             if (m_inputted_keys.size () > SCIM_TABLE_MAX_INPUTTED_KEYS ||
1148                 m_factory->m_table.is_auto_commit ())
1149                 commit_converted ();
1150
1151             // If it's a key end char, then append an empty key.
1152             if (m_factory->m_table.is_key_end_char (ch) &&
1153                 m_inputing_key == m_inputted_keys.size () -1 &&
1154                 m_inputted_keys [m_inputing_key].length () &&
1155                 m_inputing_caret == m_inputted_keys [m_inputing_key].length ()) {
1156                 ++m_inputing_key;
1157                 m_inputing_caret = 0;
1158                 m_inputted_keys.insert (m_inputted_keys.begin () + m_inputing_key, String ());
1159             }
1160         }
1161
1162         refresh_preedit ();
1163         refresh_aux_string ();
1164
1165         return true;
1166     }
1167
1168     return false;
1169 }
1170
1171 bool
1172 TableInstance::erase (bool backspace)
1173 {
1174     if (m_inputted_keys.size ()) {
1175         if (backspace && (m_inputing_key > 0 || m_inputing_caret > 0)) {
1176             if (m_inputing_caret > 0) {
1177                 --m_inputing_caret;
1178                 m_inputted_keys [m_inputing_key].erase (m_inputing_caret, 1);
1179             } else {
1180                 if (m_inputted_keys [m_inputing_key].length () == 0)
1181                     m_inputted_keys.erase (m_inputted_keys.begin () + m_inputing_key);
1182
1183                 --m_inputing_key;
1184                 m_inputing_caret = m_inputted_keys [m_inputing_key].length ();
1185
1186                 if (m_inputing_caret > 0) {
1187                     --m_inputing_caret;
1188                     m_inputted_keys [m_inputing_key].erase (m_inputing_caret, 1);
1189                 }
1190             }
1191
1192             if (m_inputted_keys [m_inputing_key].length () == 0) {
1193                 m_inputted_keys.erase (m_inputted_keys.begin () + m_inputing_key);
1194
1195                 if (m_inputing_key > 0) {
1196                     --m_inputing_key;
1197                     m_inputing_caret = m_inputted_keys [m_inputing_key].length ();
1198                 }
1199             }
1200         } else if (!backspace) {
1201             if (m_inputing_caret < m_inputted_keys [m_inputing_key].length ()) {
1202                 m_inputted_keys [m_inputing_key].erase (m_inputing_caret, 1);
1203             }
1204             if (m_inputted_keys [m_inputing_key].length () == 0) {
1205                 m_inputted_keys.erase (m_inputted_keys.begin () + m_inputing_key);
1206             }
1207             if (m_inputing_key == m_inputted_keys.size () && m_inputing_key > 0) {
1208                 --m_inputing_key;
1209                 m_inputing_caret = m_inputted_keys [m_inputing_key].length ();
1210             }
1211         } else {
1212             return true;
1213         }
1214
1215         if (m_inputted_keys.size () == 1 && m_inputted_keys [0].length () == 0) {
1216             m_inputted_keys.clear ();
1217             m_inputing_key = 0;
1218             m_inputing_caret = 0;
1219         }
1220
1221         if (m_add_phrase_mode != 1) {
1222             if (m_converted_strings.size () > m_inputing_key) {
1223                 m_converted_strings.erase (m_converted_strings.begin () + m_inputing_key, m_converted_strings.end ());
1224                 m_converted_indexes.erase (m_converted_indexes.begin () + m_inputing_key, m_converted_indexes.end ());
1225             }
1226             refresh_lookup_table ();
1227         }
1228
1229         refresh_preedit ();
1230         refresh_aux_string ();
1231         return true;
1232     }
1233     return false;
1234 }
1235
1236 bool
1237 TableInstance::space_hit ()
1238 {
1239     if (m_inputted_keys.size ()) {
1240         if (m_add_phrase_mode == 1) {
1241             if (m_factory->m_table.add_phrase (m_inputted_keys [0], m_last_committed)) {
1242                 m_add_phrase_mode = 2;
1243                 m_factory->refresh (true);
1244             } else {
1245                 m_add_phrase_mode = 3;
1246             }
1247
1248             m_inputted_keys.clear ();
1249             m_last_committed = WideString ();
1250             m_inputing_caret = m_inputing_key = 0;
1251         } else {
1252             if (m_converted_strings.size () == 0 && m_lookup_table.number_of_candidates () == 0)
1253                 return true;
1254
1255             if (m_lookup_table.number_of_candidates () && m_converted_strings.size () < m_inputted_keys.size ()) {
1256                 lookup_to_converted (m_lookup_table.get_cursor_pos ());
1257                 refresh_lookup_table ();
1258             }
1259
1260             if (m_converted_strings.size () == m_inputted_keys.size () ||
1261                 (m_converted_strings.size () == m_inputted_keys.size () - 1 &&
1262                  m_inputted_keys [m_inputing_key].length () == 0))
1263                 commit_converted ();
1264         }
1265
1266         refresh_preedit ();
1267         refresh_aux_string ();
1268
1269         return true;
1270     }
1271     return false;
1272 }
1273
1274 bool
1275 TableInstance::enter_hit ()
1276 {
1277     if (m_inputted_keys.size ()) {
1278         if (m_add_phrase_mode == 1) {
1279             if (m_factory->m_table.add_phrase (m_inputted_keys [0], m_last_committed)) {
1280                 m_add_phrase_mode = 2;
1281                 m_factory->refresh (true);
1282             } else {
1283                 m_add_phrase_mode = 3;
1284             }
1285
1286             m_inputted_keys.clear ();
1287             m_last_committed = WideString ();
1288             m_inputing_caret = m_inputing_key = 0;
1289
1290             refresh_preedit ();
1291             refresh_aux_string ();
1292         } else {
1293             reset ();
1294         }
1295         return true;
1296     }
1297
1298     m_last_committed = WideString ();
1299
1300     return false;
1301 }
1302
1303 bool
1304 TableInstance::lookup_cursor_up ()
1305 {
1306     if (m_inputted_keys.size () && m_lookup_table.number_of_candidates ()) {
1307         m_lookup_table.cursor_up ();
1308         refresh_lookup_table (true, false);
1309         refresh_preedit ();
1310         refresh_aux_string ();
1311         return true;
1312     }
1313     return false;
1314 }
1315
1316 bool
1317 TableInstance::lookup_cursor_down ()
1318 {
1319     if (m_inputted_keys.size () && m_lookup_table.number_of_candidates ()) {
1320         m_lookup_table.cursor_down ();
1321         refresh_lookup_table (true, false);
1322         refresh_preedit ();
1323         refresh_aux_string ();
1324         return true;
1325     }
1326     return false;
1327 }
1328
1329 bool
1330 TableInstance::lookup_cursor_up_to_longer ()
1331 {
1332     if (m_inputted_keys.size () && m_lookup_table.number_of_candidates ()) {
1333         //Get current lookup table cursor
1334         uint32 cursor = m_lookup_table.get_cursor_pos ();
1335         //Get current phrase length
1336         uint32 curlen = m_factory->m_table.get_phrase_length (m_lookup_table_indexes [cursor]);
1337
1338         do {
1339             m_lookup_table.cursor_up ();
1340             cursor = m_lookup_table.get_cursor_pos ();
1341             if (curlen < m_factory->m_table.get_phrase_length (m_lookup_table_indexes [cursor]))
1342                 break;
1343         } while (cursor);
1344
1345         refresh_lookup_table (true, false);
1346         refresh_preedit ();
1347         refresh_aux_string ();
1348         return true;
1349     }
1350     return false;
1351 }
1352
1353 bool
1354 TableInstance::lookup_cursor_down_to_shorter ()
1355 {
1356     if (m_inputted_keys.size () && m_lookup_table.number_of_candidates ()) {
1357         uint32 entries = m_lookup_table.number_of_candidates ();
1358         //Get current lookup table cursor
1359         uint32 cursor = m_lookup_table.get_cursor_pos ();
1360         //Get current phrase length
1361         uint32 curlen = m_factory->m_table.get_phrase_length (m_lookup_table_indexes [cursor]);
1362
1363         do {
1364             m_lookup_table.cursor_down ();
1365             cursor = m_lookup_table.get_cursor_pos ();
1366             if (curlen > m_factory->m_table.get_phrase_length (m_lookup_table_indexes [cursor]))
1367                 break;
1368         } while (cursor < entries - 1);
1369
1370         refresh_lookup_table (true, false);
1371         refresh_preedit ();
1372         refresh_aux_string ();
1373         return true;
1374     }
1375     return false;
1376 }
1377
1378 bool
1379 TableInstance::lookup_page_up ()
1380 {
1381     if (m_inputted_keys.size () &&
1382          m_lookup_table.get_current_page_size () <
1383          m_lookup_table.number_of_candidates ()) {
1384
1385         m_lookup_table.page_up ();
1386         refresh_lookup_table (true, false);
1387         refresh_preedit ();
1388         refresh_aux_string ();
1389         return true;
1390     }
1391     return false;
1392 }
1393
1394 bool
1395 TableInstance::lookup_page_down ()
1396 {
1397     if (m_inputted_keys.size () && 
1398          m_lookup_table.get_current_page_size () <
1399          m_lookup_table.number_of_candidates ()) {
1400
1401         if (!m_lookup_table.page_down ())
1402             while (m_lookup_table.page_up ()) NULL;
1403
1404         refresh_lookup_table (true, false);
1405         refresh_preedit ();
1406         refresh_aux_string ();
1407         return true;
1408     }
1409     return false;
1410 }
1411
1412 bool
1413 TableInstance::lookup_select (int index)
1414 {
1415     if (m_inputted_keys.size ()) {
1416         if (m_lookup_table.number_of_candidates () == 0)
1417             return true;
1418
1419         index += m_lookup_table.get_current_page_start ();
1420
1421         lookup_to_converted (index);
1422
1423         if (m_converted_strings.size () == m_inputted_keys.size () ||
1424             (m_converted_strings.size () == m_inputted_keys.size () - 1 &&
1425              m_inputted_keys [m_inputing_key].length () == 0))
1426             commit_converted ();
1427
1428         refresh_lookup_table ();
1429         refresh_preedit ();
1430         refresh_aux_string ();
1431
1432         return true;
1433     }
1434
1435     return false;
1436 }
1437
1438 bool
1439 TableInstance::post_process (char key)
1440 {
1441     // Auto select and commit the candidate item when an invalid key is pressed.
1442     if (m_factory->m_table.is_auto_commit () &&
1443         m_converted_strings.size () == m_inputing_key &&
1444         m_inputing_key + 1 == m_inputted_keys.size () &&
1445         m_inputing_caret == m_inputted_keys [m_inputing_key].length () &&
1446         m_lookup_table.number_of_candidates ()) {
1447
1448         lookup_to_converted (m_lookup_table.get_cursor_pos ());
1449         commit_converted ();
1450
1451         refresh_lookup_table ();
1452         refresh_preedit ();
1453         refresh_aux_string ();
1454     }
1455
1456     if (m_inputted_keys.size ()) return true;
1457
1458     if ((ispunct (key) && m_full_width_punct [m_forward?1:0]) ||
1459         ((isalnum (key) || key == 0x20) && m_full_width_letter [m_forward?1:0])) {
1460         WideString str;
1461         if (key == '.')
1462             str.push_back (0x3002);
1463         else if (key == '\\')
1464             str.push_back (0x3001);
1465         else if (key == '^') {
1466             str.push_back (0x2026);
1467             str.push_back (0x2026);
1468         } else if (key == '\"') {
1469             if (!m_double_quotation_state)
1470                 str.push_back (0x201c);
1471             else
1472                 str.push_back (0x201d);
1473             m_double_quotation_state = !m_double_quotation_state;
1474         } else if (key == '\'') {
1475             if (!m_single_quotation_state)
1476                 str.push_back (0x2018);
1477             else
1478                 str.push_back (0x2019);
1479             m_single_quotation_state = !m_single_quotation_state;
1480         } else {
1481             str.push_back (scim_wchar_to_full_width (key));
1482         }
1483
1484         commit_string (str);
1485
1486         m_last_committed = WideString ();
1487
1488         return true;
1489     }
1490
1491     return false;
1492 }
1493
1494 bool
1495 TableInstance::delete_phrase ()
1496 {
1497     if (m_lookup_table.number_of_candidates ()) {
1498         int pos       = m_lookup_table.get_cursor_pos ();
1499         uint32 offset = m_lookup_table_indexes [pos];
1500
1501         if (m_factory->m_table.delete_phrase (offset)) {
1502             m_factory->refresh (true);
1503             refresh_lookup_table ();
1504         }
1505         return true;
1506     }
1507     return false;
1508 }
1509
1510 void
1511 TableInstance::lookup_to_converted (int index)
1512 {
1513     if (index < 0 || index >= m_lookup_table.number_of_candidates ())
1514         return;
1515
1516     uint32 offset  = m_lookup_table_indexes [index];
1517     WideString str = m_factory->m_table.get_phrase (offset);
1518
1519     m_converted_strings.push_back (str);
1520     m_converted_indexes.push_back (offset);
1521
1522     if (m_inputing_key < m_converted_strings.size ()) {
1523         m_inputing_key = m_converted_strings.size ();
1524         if (m_inputing_key >= m_inputted_keys.size ())
1525             m_inputted_keys.push_back (String (""));
1526         m_inputing_caret = 0;
1527     }
1528 }
1529
1530 void
1531 TableInstance::commit_converted ()
1532 {
1533     if (m_converted_strings.size ()) {
1534         WideString res;
1535
1536         for (size_t i=0; i<m_converted_strings.size (); ++i)
1537             res += m_converted_strings [i];
1538
1539         // Hide preedit string before committing string,
1540         // to prevent some buggy clients from inserting the string into wrong place.
1541         // Preedit string will be refreshed after return from commit_converted ().
1542         hide_preedit_string ();
1543         commit_string (res);
1544
1545         if (utf8_wcstombs (m_last_committed).length () >= 255)
1546             m_last_committed = WideString ();
1547
1548         m_last_committed += res;
1549
1550         m_inputted_keys.erase (m_inputted_keys.begin (), m_inputted_keys.begin () + m_converted_strings.size ());
1551         m_inputing_key -= m_converted_strings.size ();
1552
1553         if (m_inputted_keys.size () == 1 && m_inputted_keys [0].length () == 0) {
1554             m_inputted_keys.clear ();
1555             m_inputing_key = 0;
1556             m_inputing_caret = 0;
1557         }
1558
1559         if (m_inputted_keys.size ()) {
1560             m_inputing_key = m_inputted_keys.size () - 1;
1561             m_inputing_caret = m_inputted_keys [m_inputing_key].length ();
1562         }
1563
1564         if (m_factory->m_table.is_dynamic_adjust ()){
1565             for (size_t i = 0; i < m_converted_indexes.size (); ++i) {
1566                 uint32 freq = m_factory->m_table.get_phrase_frequency (m_converted_indexes [i]);
1567                 if (freq < SCIM_GT_MAX_PHRASE_FREQ) {
1568                     uint32 delta = ((SCIM_GT_MAX_PHRASE_FREQ - freq) >> SCIM_GT_PHRASE_FREQ_DELTA_SHIFT);
1569                     freq += (delta ? delta : 1);
1570                     m_factory->m_table.set_phrase_frequency (m_converted_indexes [i], freq);
1571                 }
1572             }
1573             m_factory->refresh (false);
1574         }
1575
1576         m_converted_strings.clear ();
1577         m_converted_indexes.clear ();
1578     }
1579 }
1580
1581 void
1582 TableInstance::refresh_preedit ()
1583 {
1584     WideString preedit_string;
1585     int start = 0;
1586     int length = 0;
1587     int caret = 0;
1588     int end = 0;
1589     size_t i;
1590
1591     if (m_inputted_keys.size () == 0) {
1592         hide_preedit_string ();
1593         return;
1594     }
1595  
1596     for (i = 0; i<m_converted_strings.size (); ++i)
1597         preedit_string += m_converted_strings [i];
1598
1599     int inputted_keys = m_inputted_keys.size ();
1600
1601     if (m_inputted_keys [inputted_keys - 1].length () == 0)
1602         --inputted_keys;
1603
1604     // Fill the preedit string.
1605     if (m_factory->m_table.is_auto_fill () &&
1606         m_converted_strings.size () == inputted_keys - 1 &&
1607         m_inputing_caret == m_inputted_keys [m_inputing_key].length () &&
1608         m_lookup_table.number_of_candidates ()) {
1609
1610         uint32 offset = m_lookup_table_indexes [m_lookup_table.get_cursor_pos ()];
1611         WideString str = m_factory->m_table.get_phrase (offset);
1612
1613         start = preedit_string.length ();
1614         preedit_string += str;
1615         length = str.length ();
1616         caret = preedit_string.length ();
1617     } else {
1618         i = m_converted_strings.size ();
1619         caret = start = preedit_string.length ();
1620
1621         for (i = m_converted_strings.size (); i < inputted_keys; ++i) {
1622             if (m_factory->m_table.is_show_key_prompt ()) {
1623                 preedit_string += m_factory->m_table.get_key_prompt (m_inputted_keys [i]);
1624                 if (i == m_inputing_key)
1625                     caret += (m_factory->m_table.get_key_prompt (m_inputted_keys [i].substr (0, m_inputing_caret))).length ();
1626             } else {
1627                 preedit_string += utf8_mbstowcs (m_inputted_keys [i]);
1628                 if (i == m_inputing_key)
1629                     caret += m_inputing_caret;
1630             }
1631
1632             if (i == m_converted_strings.size ())
1633                 length = preedit_string.length () - start;
1634
1635             if (i < inputted_keys - 1)
1636                 preedit_string.push_back ((ucs4_t)' ');
1637
1638             if (i < m_inputing_key)
1639                 caret = preedit_string.length ();
1640         }
1641     }
1642     m_preedit_string = preedit_string;
1643     if (preedit_string.length () == 0) {
1644         hide_preedit_string ();
1645         return;
1646     }
1647
1648     AttributeList attrs;
1649
1650     if (length)
1651     {
1652         if (start)
1653             attrs.push_back (Attribute(0, start, SCIM_ATTR_DECORATE, SCIM_ATTR_DECORATE_UNDERLINE));
1654         attrs.push_back (Attribute(start, length, SCIM_ATTR_DECORATE, SCIM_ATTR_DECORATE_HIGHLIGHT));
1655         end = start+length;
1656         if (end < preedit_string.length())
1657             attrs.push_back (Attribute(end, preedit_string.length()- end, SCIM_ATTR_DECORATE, SCIM_ATTR_DECORATE_UNDERLINE));
1658     }
1659     update_preedit_string (preedit_string, attrs);
1660     update_preedit_caret (caret);
1661
1662     show_preedit_string ();
1663 }
1664
1665 void
1666 TableInstance::refresh_lookup_table (bool show, bool refresh)
1667 {
1668     m_lookup_table.set_page_size (m_factory->m_table.get_select_keys ().size ());
1669
1670     if (refresh) {
1671         std::vector <uint32> phrases;
1672         WideString str;
1673
1674         m_lookup_table.clear ();
1675         m_lookup_table_indexes.clear ();
1676
1677         if (m_converted_strings.size () < m_inputted_keys.size ()) {
1678
1679             String key = m_inputted_keys [m_converted_strings.size ()];
1680
1681             if (key.length () &&
1682                 m_factory->m_table.find (phrases,
1683                                          key,
1684                                          m_factory->m_user_phrase_first,
1685                                          m_factory->m_long_phrase_first)) {
1686
1687                 bool show_full_hint = m_factory->m_table.is_wildcard_key (key);
1688                 std::set<WideString> candiadtes;
1689                 for (size_t i = 0; i < phrases.size (); ++i) {
1690                     str = m_factory->m_table.get_phrase (phrases [i]);
1691
1692                     if (m_iconv.test_convert (str)) {
1693                         if (m_factory->m_show_key_hint) {
1694                             String hint = m_factory->m_table.get_key (phrases [i]);
1695
1696                             if (show_full_hint)
1697                                 str += utf8_mbstowcs (hint);
1698                             else if (hint.length () > key.length ())
1699                                 str += utf8_mbstowcs (hint.substr (key.length ()));
1700                         }
1701 #if 0
1702                         AttributeList attrs;
1703
1704                         if (m_factory->m_table.is_user_phrase (phrases [i]))
1705                             attrs.push_back (Attribute (0, str.length (), SCIM_ATTR_FOREGROUND, SCIM_RGB_COLOR(32, 32, 255)));
1706
1707                         m_lookup_table.append_candidate (str, attrs);
1708 #endif
1709                         if (candiadtes.find (str) != candiadtes.end())
1710                             continue;
1711                         candiadtes.insert (str);
1712                         m_lookup_table.append_candidate (str);
1713                         m_lookup_table_indexes.push_back (phrases [i]);
1714                     }
1715                 }
1716             }
1717         }
1718     }
1719     if (show) {
1720         if (m_lookup_table.number_of_candidates () &&
1721             (m_factory->m_table.is_always_show_lookup () ||
1722              m_inputing_key < m_inputted_keys.size () - 1 ||
1723              m_inputing_caret < m_inputted_keys [m_inputing_key].length () ||
1724              m_converted_strings.size () < m_inputted_keys.size () - 1)) {
1725             update_lookup_table (m_lookup_table);
1726         } else {        
1727             if (m_inputted_keys.size () &&
1728                 (m_inputing_caret || m_lookup_table.number_of_candidates ()))
1729             {
1730                 m_lookup_table.clear ();
1731                 update_lookup_table (m_lookup_table);
1732             }
1733             else
1734                 update_lookup_table (m_common_lookup_table);
1735         }
1736     }
1737 }
1738
1739 void
1740 TableInstance::refresh_aux_string ()
1741 {
1742     WideString    prompt;
1743     AttributeList attributes;
1744
1745     if (m_add_phrase_mode == 1) {
1746         prompt = utf8_mbstowcs (_("Input a key string for phrase: ")) + m_last_committed;
1747     } else if (m_add_phrase_mode == 2) {
1748         prompt = utf8_mbstowcs (_("Success."));
1749         attributes.push_back (Attribute (0, prompt.length (), SCIM_ATTR_FOREGROUND, SCIM_RGB_COLOR(32, 255, 32)));
1750     } else if (m_add_phrase_mode == 3) {
1751         prompt = utf8_mbstowcs (_("Failed."));
1752         attributes.push_back (Attribute (0, prompt.length (), SCIM_ATTR_FOREGROUND, SCIM_RGB_COLOR(255, 32, 32)));
1753     } else {
1754         if (!m_factory->m_show_prompt || m_inputted_keys.size () == 0) {
1755             hide_aux_string ();
1756             return;
1757         }
1758
1759         if (!m_factory->m_table.is_show_key_prompt ())
1760             prompt = m_factory->m_table.get_key_prompt (m_inputted_keys [m_inputing_key]);
1761
1762         if (m_lookup_table.number_of_candidates () && ! m_factory->m_show_key_hint) {
1763             prompt += utf8_mbstowcs (" <");
1764             unsigned int att_start = prompt.length ();
1765
1766             if (m_factory->m_table.is_show_key_prompt ())
1767                 prompt += m_factory->m_table.get_key_prompt (m_factory->m_table.get_key (
1768                             m_lookup_table_indexes [m_lookup_table.get_cursor_pos ()]));
1769             else
1770                 prompt += utf8_mbstowcs (m_factory->m_table.get_key (
1771                             m_lookup_table_indexes [m_lookup_table.get_cursor_pos ()]));
1772
1773             unsigned int att_length = prompt.length () - att_start;
1774             prompt += utf8_mbstowcs (">");
1775             attributes.push_back (Attribute (att_start, att_length, SCIM_ATTR_FOREGROUND, SCIM_RGB_COLOR(128, 128, 255)));
1776         }
1777     }
1778
1779     if (prompt.length ()) {
1780         update_aux_string (prompt, attributes);
1781         show_aux_string ();
1782     } else {
1783         hide_aux_string ();
1784     }
1785 }
1786
1787 bool
1788 TableInstance::match_key_event (const std::vector<KeyEvent>& keyvec,
1789                                       const KeyEvent& key)
1790 {
1791     std::vector<KeyEvent>::const_iterator kit; 
1792
1793     for (kit = keyvec.begin (); kit != keyvec.end (); ++kit) {
1794         if (key.code == kit->code && key.mask == kit->mask)
1795             if (!(key.mask & SCIM_KEY_ReleaseMask) || m_prev_key.code == key.code)
1796                 return true;
1797     }
1798     return false;
1799 }
1800 /*
1801 vi:ts=4:nowrap:ai:expandtab
1802 */