Refine IME switch keybinding related code.
[platform/upstream/ibus.git] / ui / gtk3 / panel.vala
1 /* vim:set et sts=4 sw=4:
2  *
3  * ibus - The Input Bus
4  *
5  * Copyright(c) 2011 Peng Huang <shawn.p.huang@gmail.com>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or(at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this program; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20  * Boston, MA  02111-1307  USA
21  */
22
23 using IBus;
24 using GLib;
25 using Gtk;
26 using Posix;
27
28 public extern const string IBUS_VERSION;
29 public extern const string BINDIR;
30
31 class Panel : IBus.PanelService {
32     private IBus.Bus m_bus;
33     private IBus.Config m_config;
34     private Gtk.StatusIcon m_status_icon;
35     private Gtk.Menu m_ime_menu;
36     private Gtk.Menu m_sys_menu;
37     private IBus.EngineDesc[] m_engines = {};
38     private CandidatePanel m_candidate_panel;
39     private Switcher m_switcher;
40     private PropertyManager m_property_manager;
41     private GLib.Pid m_setup_pid = 0;
42     private Gtk.AboutDialog m_about_dialog;
43     private Gtk.CssProvider m_css_provider;
44     private const string ACCELERATOR_SWITCH_IME_FOREWARD = "<Control>space";
45
46     private uint m_switch_keysym = 0;
47     private Gdk.ModifierType m_switch_modifiers = 0;
48
49     public Panel(IBus.Bus bus) {
50         GLib.assert(bus.is_connected());
51         // Chain up base class constructor
52         GLib.Object(connection : bus.get_connection(),
53                     object_path : "/org/freedesktop/IBus/Panel");
54
55         m_bus = bus;
56
57         // init ui
58         m_status_icon = new Gtk.StatusIcon();
59         m_status_icon.set_name("ibus-ui-gtk");
60         m_status_icon.set_title("IBus Panel");
61         m_status_icon.popup_menu.connect(status_icon_popup_menu_cb);
62         m_status_icon.activate.connect(status_icon_activate_cb);
63         m_status_icon.set_from_icon_name("ibus-keyboard");
64
65         m_candidate_panel = new CandidatePanel();
66         m_candidate_panel.page_up.connect((w) => this.page_up());
67         m_candidate_panel.page_down.connect((w) => this.page_down());
68
69         m_switcher = new Switcher();
70         bind_switch_shortcut();
71
72         m_property_manager = new PropertyManager();
73         m_property_manager.property_activate.connect((k, s) => {
74             property_activate(k, s);
75         });
76
77         state_changed();
78     }
79
80     ~Panel() {
81         unbind_switch_shortcut();
82     }
83
84     private void bind_switch_shortcut() {
85         var keybinding_manager = KeybindingManager.get_instance();
86
87         Gtk.accelerator_parse(ACCELERATOR_SWITCH_IME_FOREWARD,
88                 out m_switch_keysym, out m_switch_modifiers);
89
90         if (m_switch_keysym == 0 && m_switch_modifiers == 0) {
91             warning("Parse accelerator '%s' failed!",
92                     ACCELERATOR_SWITCH_IME_FOREWARD);
93             return;
94         }
95
96         keybinding_manager.bind(m_switch_keysym, m_switch_modifiers,
97                 (e) => handle_engine_switch(e, false));
98
99         // accelerator already has Shift mask
100         if ((m_switch_modifiers & Gdk.ModifierType.SHIFT_MASK) != 0)
101             return;
102
103         keybinding_manager.bind(m_switch_keysym,
104                 m_switch_modifiers | Gdk.ModifierType.SHIFT_MASK,
105                 (e) => handle_engine_switch(e, true));
106     }
107
108     private void unbind_switch_shortcut() {
109         var keybinding_manager = KeybindingManager.get_instance();
110
111         if (m_switch_keysym == 0 && m_switch_modifiers == 0)
112             return;
113
114         keybinding_manager.unbind(m_switch_keysym, m_switch_modifiers);
115         keybinding_manager.unbind(m_switch_keysym,
116                 m_switch_modifiers | Gdk.ModifierType.SHIFT_MASK);
117
118         m_switch_keysym = 0;
119         m_switch_modifiers = 0;
120     }
121
122     private void set_custom_font() {
123         Gdk.Display display = Gdk.Display.get_default();
124         Gdk.Screen screen = (display != null) ?
125                 display.get_default_screen() : null;
126
127         if (screen == null) {
128             warning("Could not open display.");
129             return;
130         }
131
132         bool use_custom_font = false;
133         GLib.Variant var_use_custom_font = m_config.get_value("panel",
134                                                               "use_custom_font");
135
136         if (var_use_custom_font != null) {
137             use_custom_font = var_use_custom_font.get_boolean();
138         }
139
140         if (m_css_provider != null) {
141             Gtk.StyleContext.remove_provider_for_screen(screen,
142                                                         m_css_provider);
143             m_css_provider = null;
144         }
145
146         if (use_custom_font == false) {
147             return;
148         }
149
150         string font_name = null;
151         GLib.Variant var_custom_font = m_config.get_value("panel",
152                                                           "custom_font");
153         if (var_custom_font != null) {
154             font_name = var_custom_font.dup_string();
155         }
156
157         if (font_name == null) {
158             warning("No config panel:custom_font.");
159             return;
160         }
161
162         string data_format = "GtkLabel { font: %s; }";
163         string data = data_format.printf(font_name);
164         m_css_provider = new Gtk.CssProvider();
165
166         try {
167             m_css_provider.load_from_data(data, -1);
168         } catch (GLib.Error e) {
169             warning("Failed css_provider_from_data: %s: %s", font_name,
170                                                              e.message);
171             return;
172         }
173
174         Gtk.StyleContext.add_provider_for_screen(screen,
175                                                  m_css_provider,
176                                                  Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION);
177     }
178
179     public void set_config(IBus.Config config) {
180         if (m_config != null) {
181             m_config.value_changed.disconnect(config_value_changed_cb);
182             m_config.watch(null, null);
183             m_config = null;
184         }
185
186         m_config = config;
187         if (m_config != null) {
188             m_config.value_changed.connect(config_value_changed_cb);
189             m_config.watch("general", "preload_engines");
190             m_config.watch("general", "engines_order");
191             m_config.watch("panel", "custom_font");
192             m_config.watch("panel", "use_custom_font");
193             update_engines(m_config.get_value("general", "preload_engines"),
194                            m_config.get_value("general", "engines_order"));
195         } else {
196             update_engines(null, null);
197         }
198
199         set_custom_font();
200     }
201
202     private void switch_engine(int i, bool force = false) {
203         GLib.assert(i >= 0 && i < m_engines.length);
204
205         // Do not need switch
206         if (i == 0 && !force)
207             return;
208
209         IBus.EngineDesc engine = m_engines[i];
210
211         if (!m_bus.set_global_engine(engine.get_name())) {
212             warning("Switch engine to %s failed.", engine.get_name());
213             return;
214         }
215         // set xkb layout
216         string cmdline = "setxkbmap %s".printf(engine.get_layout());
217         try {
218             if (!GLib.Process.spawn_command_line_sync(cmdline)) {
219                 warning("Switch xkb layout to %s failed.",
220                     engine.get_layout());
221             }
222         } catch (GLib.SpawnError e) {
223             warning("execute setxkblayout failed");
224         }
225     }
226
227     private void config_value_changed_cb(IBus.Config config,
228                                          string section,
229                                          string name,
230                                          Variant variant) {
231         if (section == "general" && name == "preload_engines") {
232             update_engines(variant, null);
233             return;
234         }
235
236         if (section == "panel" && (name == "custom_font" ||
237                                    name == "use_custom_font")) {
238             set_custom_font();
239             return;
240         }
241     }
242
243     private void handle_engine_switch(Gdk.Event event, bool revert) {
244         // Do not need switch IME
245         if (m_engines.length <= 1)
246             return;
247
248         uint primary_modifiers =
249             KeybindingManager.get_primary_modifier(event.key.state);
250
251         bool pressed = KeybindingManager.primary_modifier_still_pressed(
252                 event, primary_modifiers);
253         if (pressed) {
254             int i = revert ? m_engines.length - 1 : 1;
255             i = m_switcher.run(m_switch_keysym, m_switch_modifiers, event,
256                     m_engines, i);
257             if (i < 0) {
258                 debug("switch cancelled");
259             } else {
260                 GLib.assert(i < m_engines.length);
261                 switch_engine(i);
262             }
263         } else {
264             int i = revert ? m_engines.length - 1 : 1;
265             switch_engine(i);
266         }
267     }
268
269     private void update_engines(GLib.Variant? var_engines,
270                                 GLib.Variant? var_order) {
271         string[] engine_names = null;
272
273         if (var_engines != null)
274             engine_names = var_engines.dup_strv();
275         if (engine_names == null || engine_names.length == 0)
276             engine_names = {"xkb:us::eng"};
277
278         string[] order_names =
279             (var_order != null) ? var_order.dup_strv() : null;
280
281         string[] names = {};
282
283         foreach (var name in order_names) {
284             if (name in engine_names)
285                 names += name;
286         }
287
288         foreach (var name in engine_names) {
289             if (name in names)
290                 continue;
291             names += name;
292         }
293
294         var engines = m_bus.get_engines_by_names(names);
295
296         if (m_engines.length == 0) {
297             m_engines = engines;
298             switch_engine(0, true);
299         } else {
300             var current_engine = m_engines[0];
301             m_engines = engines;
302             int i;
303             for (i = 0; i < m_engines.length; i++) {
304                 if (current_engine.get_name() == engines[i].get_name()) {
305                     switch_engine(i);
306                     return;
307                 }
308             }
309             switch_engine(0, true);
310         }
311
312     }
313
314     private void show_setup_dialog() {
315         if (m_setup_pid != 0) {
316             if (Posix.kill(m_setup_pid, Posix.SIGUSR1) == 0)
317                 return;
318             m_setup_pid = 0;
319         }
320
321         string binary = GLib.Path.build_filename(BINDIR, "ibus-setup");
322         try {
323             GLib.Process.spawn_async(null,
324                                      {binary, "ibus-setup"},
325                                      null,
326                                      GLib.SpawnFlags.DO_NOT_REAP_CHILD,
327                                      null,
328                                      out m_setup_pid);
329         } catch (GLib.SpawnError e) {
330             warning("Execute %s failed! %s", binary, e.message);
331             m_setup_pid = 0;
332         }
333
334         GLib.ChildWatch.add(m_setup_pid, (pid, state) => {
335             if (pid != m_setup_pid)
336                 return;
337             m_setup_pid = 0;
338             GLib.Process.close_pid(pid);
339         });
340     }
341
342     private void show_about_dialog() {
343         if (m_about_dialog == null) {
344             m_about_dialog = new Gtk.AboutDialog();
345             m_about_dialog.set_program_name("IBus");
346             m_about_dialog.set_version(IBUS_VERSION);
347
348             string copyright = _(
349                 "Copyright (c) 2007-2012 Peng Huang\n" +
350                 "Copyright (c) 2007-2010 Red Hat, Inc.\n");
351
352             m_about_dialog.set_copyright(copyright);
353             m_about_dialog.set_license("LGPL");
354             m_about_dialog.set_comments(_("IBus is an intelligent input bus for Linux/Unix."));
355             m_about_dialog.set_website("http://code.google.com/p/ibus");
356             m_about_dialog.set_authors({"Peng Huang <shawn.p.huang@gmail.com>"});
357             m_about_dialog.set_documenters({"Peng Huang <shawn.p.huang@gmail.com>"});
358             m_about_dialog.set_translator_credits(_("translator-credits"));
359             m_about_dialog.set_logo_icon_name("ibus");
360             m_about_dialog.set_icon_name("ibus");
361         }
362
363         if (!m_about_dialog.get_visible()) {
364             m_about_dialog.run();
365             m_about_dialog.hide();
366         } else {
367             m_about_dialog.present();
368         }
369     }
370
371     private void status_icon_popup_menu_cb(Gtk.StatusIcon status_icon,
372                                            uint button,
373                                            uint activate_time) {
374         // Show system menu
375         if (m_sys_menu == null) {
376             Gtk.ImageMenuItem item;
377             m_sys_menu = new Gtk.Menu();
378
379             item = new Gtk.ImageMenuItem.from_stock(Gtk.Stock.PREFERENCES, null);
380             item.activate.connect((i) => show_setup_dialog());
381             m_sys_menu.append(item);
382
383             item = new Gtk.ImageMenuItem.from_stock(Gtk.Stock.ABOUT, null);
384             item.activate.connect((i) => show_about_dialog());
385             m_sys_menu.append(item);
386
387             m_sys_menu.append(new SeparatorMenuItem());
388
389             item = new Gtk.ImageMenuItem.from_stock(Gtk.Stock.REFRESH, null);
390             item.set_label(_("Restart"));
391             item.activate.connect((i) => m_bus.exit(true));
392             m_sys_menu.append(item);
393
394             item = new Gtk.ImageMenuItem.from_stock(Gtk.Stock.QUIT, null);
395             item.activate.connect((i) => m_bus.exit(false));
396             m_sys_menu.append(item);
397
398             m_sys_menu.show_all();
399         }
400
401         m_sys_menu.popup(null,
402                          null,
403                          m_status_icon.position_menu,
404                          0,
405                          Gtk.get_current_event_time());
406     }
407
408     private void status_icon_activate_cb(Gtk.StatusIcon status_icon) {
409         m_ime_menu = new Gtk.Menu();
410
411         // Show properties and IME switching menu
412         m_property_manager.create_menu_items(m_ime_menu);
413
414         m_ime_menu.append(new SeparatorMenuItem());
415
416         int width, height;
417         Gtk.icon_size_lookup(Gtk.IconSize.MENU, out width, out height);
418
419         // Append IMEs
420         foreach (var engine in m_engines) {
421             var language = engine.get_language();
422             var longname = engine.get_longname();
423             var item = new Gtk.ImageMenuItem.with_label(
424                 "%s - %s".printf (IBus.get_language_name(language), longname));
425             if (engine.get_icon() != "") {
426                 var icon = new IconWidget(engine.get_icon(), width);
427                  item.set_image(icon);
428             }
429             // Make a copy of engine to workaround a bug in vala.
430             // https://bugzilla.gnome.org/show_bug.cgi?id=628336
431             var e = engine;
432             item.activate.connect((item) => {
433                 for (int i = 0; i < m_engines.length; i++) {
434                     if (e == m_engines[i]) {
435                         switch_engine(i);
436                         break;
437                     }
438                 }
439             });
440             m_ime_menu.add(item);
441         }
442
443         m_ime_menu.show_all();
444
445         // Do not take focuse to avoid some focus related issues.
446         m_ime_menu.set_take_focus(false);
447         m_ime_menu.popup(null,
448                          null,
449                          m_status_icon.position_menu,
450                          0,
451                          Gtk.get_current_event_time());
452     }
453
454     /* override virtual functions */
455     public override void set_cursor_location(int x, int y,
456                                              int width, int height) {
457         m_candidate_panel.set_cursor_location(x, y, width, height);
458     }
459
460     public override void focus_in(string input_context_path) {
461     }
462
463     public override void focus_out(string input_context_path) {
464     }
465
466     public override void register_properties(IBus.PropList props) {
467         m_property_manager.set_properties(props);
468     }
469
470     public override void update_property(IBus.Property prop) {
471         m_property_manager.update_property(prop);
472     }
473
474     public override void update_preedit_text(IBus.Text text,
475                                              uint cursor_pos,
476                                              bool visible) {
477         if (visible)
478             m_candidate_panel.set_preedit_text(text, cursor_pos);
479         else
480             m_candidate_panel.set_preedit_text(null, 0);
481     }
482
483     public override void hide_preedit_text() {
484         m_candidate_panel.set_preedit_text(null, 0);
485     }
486
487     public override void update_auxiliary_text(IBus.Text text,
488                                                bool visible) {
489         m_candidate_panel.set_auxiliary_text(visible ? text : null);
490     }
491
492     public override void hide_auxiliary_text() {
493         m_candidate_panel.set_auxiliary_text(null);
494     }
495
496     public override void update_lookup_table(IBus.LookupTable table,
497                                              bool visible) {
498         m_candidate_panel.set_lookup_table(visible ? table : null);
499     }
500
501     public override void hide_lookup_table() {
502         m_candidate_panel.set_lookup_table(null);
503     }
504
505     public override void state_changed() {
506         var icon_name = "ibus-keyboard";
507
508         var engine = m_bus.get_global_engine();
509         if (engine != null)
510             icon_name = engine.get_icon();
511
512         if (icon_name[0] == '/')
513             m_status_icon.set_from_file(icon_name);
514         else
515             m_status_icon.set_from_icon_name(icon_name);
516
517         if (engine == null)
518             return;
519
520         int i;
521         for (i = 0; i < m_engines.length; i++) {
522             if (m_engines[i].get_name() == engine.get_name())
523                 break;
524         }
525
526         // engine is first engine in m_engines.
527         if (i == 0)
528             return;
529
530         // engine is not in m_engines.
531         if (i >= m_engines.length)
532             return;
533
534         for (int j = i; j > 0; j--) {
535             m_engines[j] = m_engines[j - 1];
536         }
537         m_engines[0] = engine;
538
539         string[] names = {};
540         foreach(var desc in m_engines) {
541             names += desc.get_name();
542         }
543         if (m_config != null)
544             m_config.set_value("general",
545                                "engines_order",
546                                new GLib.Variant.strv(names));
547     }
548 }