]> icculus.org git repositories - dana/openbox.git/blob - src/bindings.cc
rm a XXX
[dana/openbox.git] / src / bindings.cc
1 // -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 2; -*-
2
3 #ifdef HAVE_CONFIG_H
4 # include "../config.h"
5 #endif
6
7 #include "bindings.hh"
8 #include "screen.hh"
9 #include "openbox.hh"
10 #include "client.hh"
11 #include "frame.hh"
12 #include "python.hh"
13 #include "otk/display.hh"
14
15 extern "C" {
16 #include <X11/Xlib.h>
17
18 #include "gettext.h"
19 #define _(str) gettext(str)
20 }
21
22 #include <algorithm>
23
24 namespace ob {
25
26 static bool buttonvalue(const std::string &button, unsigned int *val)
27 {
28   if (button == "Left" || button == "1" || button == "Button1") {
29     *val |= Button1;
30   } else if (button == "Middle" || button == "2" || button == "Button2") {
31     *val |= Button2;
32   } else if (button == "Right" || button == "3" || button == "Button3") {
33     *val |= Button3;
34   } else if (button == "Up" || button == "4" || button == "Button4") {
35     *val |= Button4;
36   } else if (button == "Down" || button == "5" || button == "Button5") {
37     *val |= Button5;
38   } else
39     return false;
40   return true;
41 }
42
43 static bool modvalue(const std::string &mod, unsigned int *val)
44 {
45   if (mod == "C") {           // control
46     *val |= ControlMask;
47   } else if (mod == "S") {    // shift
48     *val |= ShiftMask;
49   } else if (mod == "A" ||    // alt/mod1
50              mod == "M" ||
51              mod == "Mod1" ||
52              mod == "M1") {
53     *val |= Mod1Mask;
54   } else if (mod == "Mod2" ||   // mod2
55              mod == "M2") {
56     *val |= Mod2Mask;
57   } else if (mod == "Mod3" ||   // mod3
58              mod == "M3") {
59     *val |= Mod3Mask;
60   } else if (mod == "W" ||    // windows/mod4
61              mod == "Mod4" ||
62              mod == "M4") {
63     *val |= Mod4Mask;
64   } else if (mod == "Mod5" ||   // mod5
65              mod == "M5") {
66     *val |= Mod5Mask;
67   } else {                    // invalid
68     return false;
69   }
70   return true;
71 }
72
73 bool Bindings::translate(const std::string &str, Binding &b,bool askey) const
74 {
75   // parse out the base key name
76   std::string::size_type keybegin = str.find_last_of('-');
77   keybegin = (keybegin == std::string::npos) ? 0 : keybegin + 1;
78   std::string key(str, keybegin);
79
80   // parse out the requested modifier keys
81   unsigned int modval = 0;
82   std::string::size_type begin = 0, end;
83   while (begin != keybegin) {
84     end = str.find_first_of('-', begin);
85
86     std::string mod(str, begin, end-begin);
87     if (!modvalue(mod, &modval)) {
88       printf(_("Invalid modifier element in key binding: %s\n"), mod.c_str());
89       return false;
90     }
91     
92     begin = end + 1;
93   }
94
95   // set the binding
96   b.modifiers = modval;
97   if (askey) {
98     KeySym sym = XStringToKeysym(const_cast<char *>(key.c_str()));
99     if (sym == NoSymbol) {
100       printf(_("Invalid Key name in key binding: %s\n"), key.c_str());
101       return false;
102     }
103     if (!(b.key = XKeysymToKeycode(**otk::display, sym)))
104       printf(_("No valid keycode for Key in key binding: %s\n"), key.c_str());
105     return b.key != 0;
106   } else {
107     return buttonvalue(key, &b.key);
108   }
109 }
110
111 static void destroytree(KeyBindingTree *tree)
112 {
113   while (tree) {
114     KeyBindingTree *c = tree->first_child;
115     delete tree;
116     tree = c;
117   }
118 }
119
120 KeyBindingTree *Bindings::buildtree(const StringVect &keylist,
121                                       PyObject *callback) const
122 {
123   if (keylist.empty()) return 0; // nothing in the list.. return 0
124
125   KeyBindingTree *ret = 0, *p;
126
127   StringVect::const_reverse_iterator it, end = keylist.rend();
128   for (it = keylist.rbegin(); it != end; ++it) {
129     p = ret;
130     ret = new KeyBindingTree();
131     if (!p) {
132       // this is the first built node, the bottom node of the tree
133       ret->chain = false;
134       ret->callbacks.push_back(callback);
135     }
136     ret->first_child = p;
137     if (!translate(*it, ret->binding)) {
138       destroytree(ret);
139       ret = 0;
140       break;
141     }
142   }
143   return ret;
144 }
145
146
147 Bindings::Bindings()
148   : _curpos(&_keytree),
149     _resetkey(0,0),
150     _timer((otk::Timer *) 0),
151     _keybgrab_callback(0)
152 {
153 //  setResetKey("C-g"); // set the default reset key
154 }
155
156
157 Bindings::~Bindings()
158 {
159   if (_timer)
160     delete _timer;
161
162   removeAllKeys();
163   //removeAllButtons(); // this is done by each client as they are unmanaged
164   removeAllEvents();
165 }
166
167
168 void Bindings::assimilate(KeyBindingTree *node)
169 {
170   KeyBindingTree *a, *b, *tmp, *last;
171
172   if (!_keytree.first_child) {
173     // there are no nodes at this level yet
174     _keytree.first_child = node;
175   } else {
176     a = _keytree.first_child;
177     last = a;
178     b = node;
179     while (a) {
180       last = a;
181       if (a->binding != b->binding) {
182         a = a->next_sibling;
183       } else {
184         tmp = b;
185         b = b->first_child;
186         delete tmp;
187         a = a->first_child;
188       }
189     }
190     if (last->binding != b->binding)
191       last->next_sibling = b;
192     else {
193       last->first_child = b->first_child;
194       delete b;
195     }
196   }
197 }
198
199
200 KeyBindingTree *Bindings::find(KeyBindingTree *search,
201                                  bool *conflict) const {
202   *conflict = false;
203   KeyBindingTree *a, *b;
204   a = _keytree.first_child;
205   b = search;
206   while (a && b) {
207     if (a->binding != b->binding) {
208       a = a->next_sibling;
209     } else {
210       if (a->chain == b->chain) {
211         if (!a->chain) {
212           // found it! (return the actual id, not the search's)
213           return a;
214         }
215       } else {
216         *conflict = true;
217         return 0; // the chain status' don't match (conflict!)
218       }
219       b = b->first_child;
220       a = a->first_child;
221     }
222   }
223   return 0; // it just isn't in here
224 }
225
226
227 bool Bindings::addKey(const StringVect &keylist, PyObject *callback)
228 {
229   KeyBindingTree *tree, *t;
230   bool conflict;
231
232   if (!(tree = buildtree(keylist, callback)))
233     return false; // invalid binding requested
234
235   t = find(tree, &conflict);
236   if (conflict) {
237     // conflicts with another binding
238     destroytree(tree);
239     return false;
240   }
241
242   if (t) {
243     // already bound to something
244     t->callbacks.push_back(callback);
245     destroytree(tree);
246   } else {
247     // grab the server here to make sure no key pressed go missed
248     otk::display->grab();
249     grabKeys(false);
250
251     // assimilate this built tree into the main tree
252     assimilate(tree); // assimilation destroys/uses the tree
253
254     grabKeys(true); 
255     otk::display->ungrab();
256   }
257  
258   Py_INCREF(callback);
259
260   return true;
261 }
262
263 /*
264 bool Bindings::removeKey(const StringVect &keylist, PyObject *callback)
265 {
266   assert(false); // XXX: function not implemented yet
267
268   KeyBindingTree *tree;
269   bool conflict;
270
271   if (!(tree = buildtree(keylist, 0)))
272     return false; // invalid binding requested
273
274   KeyBindingTree *t = find(tree, &conflict);
275   if (t) {
276     CallbackList::iterator it = std::find(t->callbacks.begin(),
277                                           t->callbacks.end(),
278                                           callback);
279     if (it != t->callbacks.end()) {
280       // grab the server here to make sure no key pressed go missed
281       otk::display->grab();
282       grabKeys(false);
283       
284       _curpos = &_keytree;
285       
286       // XXX do shit here ...
287       Py_XDECREF(*it);
288       
289       grabKeys(true);
290       otk::display->ungrab();
291       
292       return true;
293     }
294   }
295   return false;
296 }
297 */
298
299 void Bindings::setResetKey(const std::string &key)
300 {
301   Binding b(0, 0);
302   if (translate(key, b)) {
303     // grab the server here to make sure no key pressed go missed
304     otk::display->grab();
305     grabKeys(false);
306     _resetkey.key = b.key;
307     _resetkey.modifiers = b.modifiers;
308     grabKeys(true);
309     otk::display->ungrab();
310   }
311 }
312
313
314 static void remove_branch(KeyBindingTree *first)
315 {
316   KeyBindingTree *p = first;
317
318   while (p) {
319     if (p->first_child)
320       remove_branch(p->first_child);
321     KeyBindingTree *s = p->next_sibling;
322     while(!p->callbacks.empty()) {
323       Py_XDECREF(p->callbacks.front());
324       p->callbacks.pop_front();
325     }
326     delete p;
327     p = s;
328   }
329 }
330
331
332 void Bindings::removeAllKeys()
333 {
334   grabKeys(false);
335   if (_keytree.first_child) {
336     remove_branch(_keytree.first_child);
337     _keytree.first_child = 0;
338   }
339   grabKeys(true);
340 }
341
342
343 void Bindings::grabKeys(bool grab)
344 {
345   for (int i = 0; i < ScreenCount(**otk::display); ++i) {
346     Screen *sc = openbox->screen(i);
347     if (!sc) continue; // not a managed screen
348     Window root = otk::display->screenInfo(i)->rootWindow();
349
350     KeyBindingTree *p = _curpos->first_child;
351     while (p) {
352       if (grab) {
353         otk::display->grabKey(p->binding.key, p->binding.modifiers,
354                                 root, false, GrabModeAsync, GrabModeAsync,
355                                 false);
356       }
357       else
358         otk::display->ungrabKey(p->binding.key, p->binding.modifiers,
359                                   root);
360       p = p->next_sibling;
361     }
362
363     if (_resetkey.key)
364       if (grab)
365         otk::display->grabKey(_resetkey.key, _resetkey.modifiers,
366                                 root, false, GrabModeAsync, GrabModeAsync,
367                                 false);
368       else
369         otk::display->ungrabKey(_resetkey.key, _resetkey.modifiers,
370                                   root);
371   }
372 }
373
374
375 bool Bindings::grabKeyboard(int screen, PyObject *callback)
376 {
377   assert(callback);
378   if (_keybgrab_callback) return false; // already grabbed
379
380   if (!openbox->screen(screen))
381     return false; // the screen is not managed
382   
383   Window root = otk::display->screenInfo(screen)->rootWindow();
384   if (XGrabKeyboard(**otk::display, root, false, GrabModeAsync,
385                     GrabModeAsync, CurrentTime))
386     return false;
387   _keybgrab_callback = callback;
388   return true;
389 }
390
391
392 void Bindings::ungrabKeyboard()
393 {
394   if (!_keybgrab_callback) return; // not grabbed
395
396   _keybgrab_callback = 0;
397   XUngrabKeyboard(**otk::display, CurrentTime);
398   XUngrabPointer(**otk::display, CurrentTime);
399 }
400
401
402 bool Bindings::grabPointer(int screen)
403 {
404   if (!openbox->screen(screen))
405     return false; // the screen is not managed
406   
407   Window root = otk::display->screenInfo(screen)->rootWindow();
408   XGrabPointer(**otk::display, root, false, 0, GrabModeAsync,
409                GrabModeAsync, None, None, CurrentTime);
410   return true;
411 }
412
413
414 void Bindings::ungrabPointer()
415 {
416   XUngrabPointer(**otk::display, CurrentTime);
417 }
418
419
420 void Bindings::fireKey(int screen, unsigned int modifiers, unsigned int key,
421                        Time time, KeyAction::KA action)
422 {
423   if (_keybgrab_callback) {
424     Client *c = openbox->focusedClient();
425     KeyData data(screen, c, time, modifiers, key, action);
426     python_callback(_keybgrab_callback, &data);
427   }
428   
429   // KeyRelease events only occur during keyboard grabs
430   if (action == KeyAction::Release) return;
431     
432   if (key == _resetkey.key && modifiers == _resetkey.modifiers) {
433     resetChains(this);
434   } else {
435     KeyBindingTree *p = _curpos->first_child;
436     while (p) {
437       if (p->binding.key == key && p->binding.modifiers == modifiers) {
438         if (p->chain) {
439           if (_timer)
440             delete _timer;
441           _timer = new otk::Timer(5000, // 5 second timeout
442                                   (otk::Timer::TimeoutHandler)resetChains,
443                                   this);
444           // grab the server here to make sure no key presses get missed
445           otk::display->grab();
446           grabKeys(false);
447           _curpos = p;
448           grabKeys(true);
449           otk::display->ungrab();
450         } else {
451           Client *c = openbox->focusedClient();
452           KeyData data(screen, c, time, modifiers, key, action);
453           CallbackList::iterator it, end = p->callbacks.end();
454           for (it = p->callbacks.begin(); it != end; ++it)
455             python_callback(*it, &data);
456           resetChains(this);
457         }
458         break;
459       }
460       p = p->next_sibling;
461     }
462   }
463 }
464
465 void Bindings::resetChains(Bindings *self)
466 {
467   if (self->_timer) {
468     delete self->_timer;
469     self->_timer = (otk::Timer *) 0;
470   }
471   // grab the server here to make sure no key pressed go missed
472   otk::display->grab();
473   self->grabKeys(false);
474   self->_curpos = &self->_keytree;
475   self->grabKeys(true);
476   otk::display->ungrab();
477 }
478
479
480 bool Bindings::addButton(const std::string &but, MouseContext::MC context,
481                            MouseAction::MA action, PyObject *callback)
482 {
483   assert(context >= 0 && context < MouseContext::NUM_MOUSE_CONTEXT);
484   
485   Binding b(0,0);
486   if (!translate(but, b, false))
487     return false;
488
489   ButtonBindingList::iterator it, end = _buttons[context].end();
490
491   // look for a duplicate binding
492   for (it = _buttons[context].begin(); it != end; ++it)
493     if ((*it)->binding.key == b.key &&
494         (*it)->binding.modifiers == b.modifiers) {
495       break;
496     }
497
498   ButtonBinding *bind;
499   
500   // the binding didnt exist yet, add it
501   if (it == end) {
502     bind = new ButtonBinding();
503     bind->binding.key = b.key;
504     bind->binding.modifiers = b.modifiers;
505     _buttons[context].push_back(bind);
506     // grab the button on all clients
507     for (int sn = 0; sn < ScreenCount(**otk::display); ++sn) {
508       Screen *s = openbox->screen(sn);
509       if (!s) continue; // not managed
510       Client::List::iterator c_it, c_end = s->clients.end();
511       for (c_it = s->clients.begin(); c_it != c_end; ++c_it) {
512         grabButton(true, bind->binding, context, *c_it);
513       }
514     }
515   } else
516     bind = *it;
517   bind->callbacks[action].push_back(callback);
518   Py_INCREF(callback);
519   return true;
520 }
521
522 void Bindings::removeAllButtons()
523 {
524   for (int i = 0; i < MouseContext::NUM_MOUSE_CONTEXT; ++i) {
525     ButtonBindingList::iterator it, end = _buttons[i].end();
526     for (it = _buttons[i].begin(); it != end; ++it) {
527       for (int a = 0; a < MouseAction::NUM_MOUSE_ACTION; ++a) {
528         while (!(*it)->callbacks[a].empty()) {
529           Py_XDECREF((*it)->callbacks[a].front());
530           (*it)->callbacks[a].pop_front();
531         }
532       }
533       // ungrab the button on all clients
534       for (int sn = 0; sn < ScreenCount(**otk::display); ++sn) {
535         Screen *s = openbox->screen(sn);
536         if (!s) continue; // not managed
537         Client::List::iterator c_it, c_end = s->clients.end();
538         for (c_it = s->clients.begin(); c_it != c_end; ++c_it) {
539           grabButton(false, (*it)->binding, (MouseContext::MC)i, *c_it);
540         }
541       }
542     }
543   }
544 }
545
546 void Bindings::grabButton(bool grab, const Binding &b,
547                           MouseContext::MC context, Client *client)
548 {
549   Window win;
550   int mode = GrabModeAsync;
551   unsigned int mask;
552   switch(context) {
553   case MouseContext::Frame:
554     win = client->frame->window();
555     mask = ButtonPressMask | ButtonMotionMask | ButtonReleaseMask;
556     break;
557   case MouseContext::Window:
558     win = client->frame->plate();
559     mode = GrabModeSync; // this is handled in fireButton
560     mask = ButtonPressMask; // can't catch more than this with Sync mode
561                             // the release event is manufactured by the
562                             // master buttonPressHandler
563     break;
564   default:
565     // any other elements already get button events, don't grab on them
566     return;
567   }
568   if (grab)
569     otk::display->grabButton(b.key, b.modifiers, win, false, mask, mode,
570                              GrabModeAsync, None, None, false);
571   else
572     otk::display->ungrabButton(b.key, b.modifiers, win);
573 }
574
575 void Bindings::grabButtons(bool grab, Client *client)
576 {
577   for (int i = 0; i < MouseContext::NUM_MOUSE_CONTEXT; ++i) {
578     ButtonBindingList::iterator it, end = _buttons[i].end();
579     for (it = _buttons[i].begin(); it != end; ++it)
580       grabButton(grab, (*it)->binding, (MouseContext::MC)i, client);
581   }
582 }
583
584 void Bindings::fireButton(MouseData *data)
585 {
586   if (data->context == MouseContext::Window) {
587     // Replay the event, so it goes to the client
588     XAllowEvents(**otk::display, ReplayPointer, data->time);
589   }
590   
591   ButtonBindingList::iterator it, end = _buttons[data->context].end();
592   for (it = _buttons[data->context].begin(); it != end; ++it)
593     if ((*it)->binding.key == data->button &&
594         (*it)->binding.modifiers == data->state) {
595       CallbackList::iterator c_it,c_end = (*it)->callbacks[data->action].end();
596       for (c_it = (*it)->callbacks[data->action].begin();
597            c_it != c_end; ++c_it)
598         python_callback(*c_it, data);
599     }
600 }
601
602
603 bool Bindings::addEvent(EventAction::EA action, PyObject *callback)
604 {
605   if (action < 0 || action >= EventAction::NUM_EVENTS) {
606     return false;
607   }
608 #ifdef    XKB
609   if (action == EventAction::Bell && _eventlist[action].empty())
610     XkbSelectEvents(**otk::display, XkbUseCoreKbd,
611                     XkbBellNotifyMask, XkbBellNotifyMask);
612 #endif // XKB
613   _eventlist[action].push_back(callback);
614   Py_INCREF(callback);
615   return true;
616 }
617
618 bool Bindings::removeEvent(EventAction::EA action, PyObject *callback)
619 {
620   if (action < 0 || action >= EventAction::NUM_EVENTS) {
621     return false;
622   }
623   
624   CallbackList::iterator it = std::find(_eventlist[action].begin(),
625                                         _eventlist[action].end(),
626                                         callback);
627   if (it != _eventlist[action].end()) {
628     Py_XDECREF(*it);
629     _eventlist[action].erase(it);
630 #ifdef    XKB
631     if (action == EventAction::Bell && _eventlist[action].empty())
632       XkbSelectEvents(**otk::display, XkbUseCoreKbd,
633                       XkbBellNotifyMask, 0);
634 #endif // XKB
635     return true;
636   }
637   return false;
638 }
639
640 void Bindings::removeAllEvents()
641 {
642   for (int i = 0; i < EventAction::NUM_EVENTS; ++i) {
643     while (!_eventlist[i].empty()) {
644       Py_XDECREF(_eventlist[i].front());
645       _eventlist[i].pop_front();
646     }
647   }
648 }
649
650 void Bindings::fireEvent(EventData *data)
651 {
652   CallbackList::iterator c_it, c_end = _eventlist[data->action].end();
653   for (c_it = _eventlist[data->action].begin(); c_it != c_end; ++c_it)
654     python_callback(*c_it, data);
655 }
656
657 }