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