e48c18612d105abdcf2023fa1d398a0919b9718c
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / libgtk2ui / gtk2_event_loop.cc
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/ui/libgtk2ui/gtk2_event_loop.h"
6
7 #include <gdk/gdk.h>
8 #include <gdk/gdkx.h>
9 #include <gtk/gtk.h>
10 #include <X11/X.h>
11
12 #include "base/memory/singleton.h"
13 #include "ui/gfx/x/x11_types.h"
14
15 namespace libgtk2ui {
16
17 // static
18 Gtk2EventLoop* Gtk2EventLoop::GetInstance() {
19   return Singleton<Gtk2EventLoop>::get();
20 }
21
22 Gtk2EventLoop::Gtk2EventLoop() {
23   gdk_event_handler_set(DispatchGdkEvent, NULL, NULL);
24 }
25
26 Gtk2EventLoop::~Gtk2EventLoop() {
27   gdk_event_handler_set(reinterpret_cast<GdkEventFunc>(gtk_main_do_event),
28                         NULL, NULL);
29 }
30
31 // static
32 void Gtk2EventLoop::DispatchGdkEvent(GdkEvent* gdk_event, gpointer) {
33   switch (gdk_event->type) {
34     case GDK_KEY_PRESS:
35     case GDK_KEY_RELEASE:
36       ProcessGdkEventKey(gdk_event->key);
37       break;
38     default:
39       break;  // Do nothing.
40   }
41
42   gtk_main_do_event(gdk_event);
43 }
44
45 // static
46 void Gtk2EventLoop::ProcessGdkEventKey(const GdkEventKey& gdk_event_key) {
47   // This function translates GdkEventKeys into XKeyEvents and puts them to
48   // the X event queue.
49   //
50   // base::MessagePumpX11 is using the X11 event queue and all key events should
51   // be processed there.  However, there are cases(*1) that GdkEventKeys are
52   // created instead of XKeyEvents.  In these cases, we have to translate
53   // GdkEventKeys to XKeyEvents and puts them to the X event queue so our main
54   // event loop can handle those key events.
55   //
56   // (*1) At least ibus-gtk in async mode creates a copy of user's key event and
57   // pushes it back to the GDK event queue.  In this case, there is no
58   // corresponding key event in the X event queue.  So we have to handle this
59   // case.  ibus-gtk is used through gtk-immodule to support IMEs.
60
61   XEvent x_event = {0};
62   x_event.xkey.type =
63       gdk_event_key.type == GDK_KEY_PRESS ? KeyPress : KeyRelease;
64   x_event.xkey.send_event = gdk_event_key.send_event;
65   x_event.xkey.display = gfx::GetXDisplay();
66   x_event.xkey.window = GDK_WINDOW_XID(gdk_event_key.window);
67   x_event.xkey.root = DefaultRootWindow(x_event.xkey.display);
68   x_event.xkey.time = gdk_event_key.time;
69   x_event.xkey.state = gdk_event_key.state;
70   x_event.xkey.keycode = gdk_event_key.hardware_keycode;
71   x_event.xkey.same_screen = true;
72
73   XPutBackEvent(x_event.xkey.display, &x_event);
74 }
75
76 }  // namespace libgtk2ui