]> git.tdb.fi Git - libs/gui.git/blob - source/input/keyboard.cpp
ab2f9eae3b1e18a13edfb110251cbfa1155866ca
[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 "keyboard.h"
12 #include "keys.h"
13
14 #define MAPVK_VK_TO_VSC 0
15
16 namespace Msp {
17 namespace Input {
18
19 Keyboard::Keyboard(Graphics::Window &w):
20         window(w)
21 {
22         name = "Keyboard";
23
24         buttons.resize(N_KEYS_, false);
25
26         window.signal_input_event.connect(sigc::mem_fun(this, &Keyboard::input_event));
27 }
28
29 std::string Keyboard::get_button_name(unsigned btn) const
30 {
31         if(btn==0)
32                 return "None";
33 #ifndef WIN32
34         const char *str = XKeysymToString(key_to_sys(btn));
35         if(!str)
36                 return Device::get_button_name(btn);
37         return str;
38 #else
39         char buf[128];
40         unsigned scan = MapVirtualKey(key_to_sys(btn), MAPVK_VK_TO_VSC);
41         if(!GetKeyNameText(scan<<16, buf, sizeof(buf)))
42                 return Device::get_button_name(btn);
43         return buf;
44 #endif
45 }
46
47 void Keyboard::input_event(const Graphics::Window::Event &event)
48 {
49 #ifdef WIN32
50         switch(event.msg)
51         {
52         case WM_KEYDOWN:
53         case WM_KEYUP:
54                 set_button_state(key_from_sys(event.wparam), event.msg==WM_KEYDOWN, true);
55                 break;
56         case WM_CHAR:
57                 signal_character.emit(event.wparam);
58                 break;
59         }
60 #else
61         switch(event.xevent.type)
62         {
63         case KeyPress:
64         case KeyRelease:
65                 {
66                         KeySym keysym = XLookupKeysym(const_cast<XKeyEvent *>(&event.xevent.xkey), 0);
67                         if(keysym!=NoSymbol)
68                                 if(unsigned key = key_from_sys(keysym))
69                                         set_button_state(key, 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