]> git.tdb.fi Git - libs/gui.git/blob - source/input/keyboard.cpp
ea66cf28ab11aa9d74f55680293336f4e5efae83
[libs/gui.git] / source / input / keyboard.cpp
1 #ifdef WIN32
2 #include <windows.h>
3 #else
4 #include <X11/Xlib.h>
5 #include <X11/Xutil.h>
6 #endif
7 #include <msp/graphics/display.h>
8 #include <msp/graphics/window.h>
9 #include <msp/graphics/display_priv.h>
10 #include <msp/graphics/window_priv.h>
11 #include <msp/strings/format.h>
12 #include "keyboard.h"
13 #include "keys.h"
14
15 #define MAPVK_VK_TO_VSC 0
16
17 namespace Msp {
18 namespace Input {
19
20 Keyboard::Keyboard(Graphics::Window &w):
21         window(w)
22 {
23         name = "Keyboard";
24
25         buttons.resize(N_KEYS_, false);
26
27         window.signal_input_event.connect(sigc::mem_fun(this, &Keyboard::input_event));
28 }
29
30 std::string Keyboard::get_button_name(unsigned btn) const
31 {
32         if(btn==0)
33                 return "None";
34 #ifndef WIN32
35         const char *str = XKeysymToString(key_to_sys(btn));
36         if(!str)
37                 return format("Key %d", btn);
38         return str;
39 #else
40         char buf[128];
41         unsigned scan = MapVirtualKey(key_to_sys(btn), MAPVK_VK_TO_VSC);
42         if(!GetKeyNameText(scan<<16, buf, sizeof(buf)))
43                 return format("Key %d", btn);
44         return buf;
45 #endif
46 }
47
48 void Keyboard::input_event(const Graphics::Window::Event &event)
49 {
50 #ifdef WIN32
51         switch(event.msg)
52         {
53         case WM_KEYDOWN:
54         case WM_KEYUP:
55                 set_button_state(key_from_sys(event.wparam), event.msg==WM_KEYDOWN, true);
56                 break;
57         case WM_CHAR:
58                 signal_character.emit(event.wparam);
59                 break;
60         }
61 #else
62         switch(event.xevent.type)
63         {
64         case KeyPress:
65         case KeyRelease:
66                 {
67                         KeySym keysym = XKeycodeToKeysym(window.get_display().get_private().display, event.xevent.xkey.keycode, 0);
68                         if(keysym!=NoSymbol)
69                                 set_button_state(key_from_sys(keysym), event.xevent.type==KeyPress, true);
70                         if(event.xevent.type==KeyPress)
71                         {
72                                 char ch;
73                                 if(XLookupString(const_cast<XKeyEvent *>(&event.xevent.xkey), &ch, 1, 0, 0))
74                                         // XLookupString always returns Latin-1
75                                         signal_character.emit(static_cast<unsigned char>(ch));
76                         }
77                 }
78                 break;
79         }
80 #endif
81 }
82
83 } // namespace Input
84 } // namespace Msp