~gestikk/gestikk/gestikk-0.5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
# -*- coding: utf-8 -*-
"""
    GESTIKK
    Version %%VERSION%%

    Gestikk, a mouse gesture recognition application
    Copyright (C) 2007-2008:
    Friedrich 'fred.reichbier' Weber (2007-10-08) and
    Jonas 'Dauerbaustelle' Haag (2008)

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
"""
from __future__ import division

VERSION = '%%VERSION%%'

import sys
import os
import os.path
import gettext
import locale
import math
import subprocess
import shlex

import virtkey

import ConfigParser
import xml.etree.ElementTree as ETree
import condparse

# wnck
import wnck
import gtk
import gtk.glade

if not os.path.isdir(os.path.expanduser('~/.gestikk')):
    os.mkdir(os.path.expanduser('~/.gestikk'))
CONFIG_FILE = os.path.expanduser('~/.gestikk/gestikk.conf')
GESTURE_FILE = os.path.expanduser('~/.gestikk/gestures.xml')
BUGS_URL = 'https://bugs.launchpad.net/gestikk'
TRANSLATORS = """%%TRANSLATORS%%"""

def get_basedir():
    """ func to get the basedir, from exaile """
    basedir = os.path.dirname(os.path.realpath(__file__))
    if not os.path.exists(os.path.join(basedir, "gestikk.py")):
        if os.path.exists(os.path.join(os.getcwd(), "gestikk.py")):
            basedir = os.getcwd()
        elif os.path.exists(os.path.join(os.path.normpath(os.path.join(basedir, '..')), 'gestikk.py')):
            basedir = os.path.normpath(os.path.join(basedir, '..'))
        else:
            basedir = '/usr/share/gestikk'
    return basedir

basedir = get_basedir()
sys.path.insert(0, basedir)
os.chdir(basedir)
BASEDIR = basedir

def get_gpl():
    """ return GPL license text """
    try:
        gpl = file('/usr/share/common-licenses/GPL-2', 'r')
    except:
        return "gestikk is released under the terms of the GNU GPL v2, which you can find on http://www.gnu.org/licenses/gpl-2.0.html"
    else:
        g = gpl.read()
        gpl.close()
        return g

def get_path(kind):
    """ return path for `kind`; linux-only at the moment
        :param kind: one of 'pixmap', 'icon'
    """
    return {'pixmap':'/usr/share/pixmaps',
            'icon':'/usr/share/icons',
            'gladefile':'/usr/share/gestikk',
            'executable':'/usr/bin'}.get(kind, '')

def get_file(name, kind):
    """ get a file. I'll try to search it in-place, then system-wide; linux-only at the moment
        :param kind: see get_path
    """
    if os.path.exists(os.path.join(BASEDIR, name)): # in-place
        return os.path.join(BASEDIR, name)
    elif os.path.exists(os.path.join(BASEDIR, 'media', name)):
        return os.path.join(BASEDIR, 'media', name)
    else: # system-wide
        path = get_path(kind)
        if not path or not os.path.exists(os.path.join(path, name)):
            raise Exception("Could not find file '%s' which should be a %s. Please report a bug at %s." % (name, kind, BUGS_URL))
            return ''
        else:
            return os.path.join(path, name)

def dict_unzip(dic):
    """ unzip {1:[2,3,4]} to [2,3,4] """
    re = []
    for key, value in dic.iteritems():
        re += value
    return re

def execute(cmd):
    """ Execute `cmd` using subprocess """
    splitted = shlex.split(cmd.encode('iso-8859-1')) # That piece of code is nearly hell on earth. shlex does not want unicode: TODO
    subprocess.Popen(splitted)

def _get_09(gesture, size=150):
    """ calculate the 0,0 point """
    point0 = [0, 0] # the zero point
    point9 = [0, 0] # the last point
    # imagine a rectangle:
    # P0 ------------------------
    # |                          |
    # |                          |
    # --------------------------P9
    # P0: point0
    # P9: point9
    # ... easy, isn't it?
    point = point0[:]
    first = True
    for g in gesture:
        if first:
            new_point = (point[0]+g[0]*size-10, point[1]+g[1]*size)
        else:
            new_point = (point[0]+g[0]*size, point[1]+g[1]*size)
        # Set Point0
        if new_point[0] < point0[0]:
            point0[0] = new_point[0]
        if new_point[1] < point0[1]:
            point0[1] = new_point[1]
        # Set Point9
        if abs(new_point[0]) > point9[0]:
            point9[0] = abs(new_point[0])
        if abs(new_point[1]) > point9[1]:
            point9[1] = abs(new_point[1])
        point = new_point
        first = False
    return point0, point9

def gesture_to_pixmap(gesture, size=150, color='#0000FF'):
    point0, point9 = _get_09(gesture, size)
    point = (-point0[0]+size//3, -point0[1]+size//3)

    img_size = (int(point9[0]+(size*(4/5))), int(point9[1]+(size*(4/5))))

    color = gtk.gdk.color_parse(color)
    bg = gtk.gdk.color_parse('#FFFFFF')
    pixmap = gtk.gdk.Pixmap(None, img_size[0], img_size[1], 24)
    gc = gtk.gdk.GC(pixmap)
    gc.set_rgb_fg_color(color)
    gc.set_rgb_bg_color(bg)
    gc.set_line_attributes(2, gtk.gdk.LINE_SOLID, gtk.gdk.CAP_NOT_LAST, gtk.gdk.JOIN_MITER)

    # clear
    gc.set_rgb_fg_color(bg)
    pixmap.draw_rectangle(gc, True, 0, 0, img_size[0], img_size[1])
    gc.set_rgb_fg_color(color)

    # draw the start point
    ps = max(size // 35, 1)
    pixmap.draw_rectangle(gc, True, point[0]-ps, point[1]-ps, 2*ps, 2*ps)

    first = True
    for g in gesture:
        if first:
            new_point = (point[0]+g[0]*size-10, point[1]+g[1]*size)
        else:
            new_point = (point[0]+g[0]*size, point[1]+g[1]*size)
        pixmap.draw_lines(gc, [point, new_point])
        point = new_point
        first = False
        # set the color
    return pixmap

def pixmap_to_pixbuf(pm, transparent_color=None):
    """ convert a pixmap to pixbuf
        :param transparent_color: tripel of rgb or None
    """
    pw, ph = pm.get_size()
    pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, pw, ph)
    pb.get_from_drawable(pm, pm.get_colormap(), 0, 0, 0, 0, pw, ph)
    if transparent_color:
        transparent_color = [chr(t) for t in transparent_color]
        pb = pb.add_alpha(True, transparent_color[0], transparent_color[1], transparent_color[2])
    return pb

def simulate_keys(keys):
    """ simulate the keys using python-virtkey
        :param k: (modifiers, keysym); returned by keystroke_to_x11
    """
    modifiers, key = keys

    v = virtkey.virtkey()
    if modifiers:
        v.lock_mod(modifiers)
    try:
        v.press_keysym(key)
        v.release_keysym(key)
    finally:
        if modifiers:
            v.unlock_mod(modifiers)

def keystroke_to_x11(keystroke):
    """ convert "CTRL+Shift+T" to (1<<2 | 1<<0, 28)
        :param keystroke: The keystroke string.
                         - can handle at least one 'real' key
                         - only ctrl, shift and alt supported yet (case-insensitive)
        :returns: tuple: (modifiers, keysym)
        :see: http://ubuntuforums.org/showthread.php?p=4441207&postcount=5
    """
    modifiers = 0
    key = ""
    splitted = keystroke.split("+")
    for stroke in splitted:
        lstroke = stroke.lower()
        if lstroke == "ctrl" or lstroke == "control":
            modifiers |= (1 << 2)
        elif lstroke == "shift":
            modifiers |= (1 << 0)
        elif lstroke == "alt":
            modifiers |= (1 << 3) # TODO: right?
        else: # is a ordinary key (Only one)
            key = gtk.gdk.keyval_from_name(stroke)
    return (modifiers, key)

def gesture_to_string(gesture):
    """ transform python-gesture to a unicode arrow string """
    # TODO
    s = u''
    for g in gesture:
        if g == (1, 0):
            s += u'\x2192'
        elif g == (-1, 0):
            s += u'\x2190'
        elif g == (0, 1):
            s += u'\x2193'
        elif g == (0, -1):
            s += u'\x2191'
        elif g == (1, 1):
            s += u'\x2198'
        elif g == (1, -1):
            s += u'\x2197'
        elif g == (-1, 1):
            s += u'\x2199'
        elif g == (-1, -1):
            s += u'\x2196'
    return s

def condition_handler_setup(wnckh):
    """ return a condition handler (see condparse)
        :param wnckh: Is the WNCKHandler()
    """
    ch = condparse.ConditionHandler()
    ch.add_function('activeApplication', lambda appname: wnckh.get_active_app_name() == appname)
    ch.add_function('activeWorkspace', lambda workspace_str: str(wnckh.get_active_workspace_number()) == workspace_str)
    ch.add_function('activeWindowTitle', lambda title: wnckh.get_active_window_title() == title)
    # startswith
    ch.add_function('activeApplication_startswith', lambda sw: wnckh.get_active_app_name().startswith(sw))
    ch.add_function('activeWindowTitle_startswith', lambda sw: wnckh.get_active_window_title().startswith(sw))
    # endswithi
    ch.add_function('activeApplication_endswith', lambda sw: wnckh.get_active_app_name().endswith(sw))
    ch.add_function('activeWindowTitle_endswith', lambda sw: wnckh.get_active_window_title().endswith(sw))
    # contains
    ch.add_function('activeApplication_contains', lambda sw: sw in wnckh.get_active_app_name())
    ch.add_function('activeWindowTitle_contains', lambda sw: sw in wnckh.get_active_window_title())
    return ch

def dict_to_objects(dic, keyattr='key', valueattr='value'):
    """ convert a dict to a list of objects """
    class Dummy():
        def __init__(self):
            pass

    objs = []
    for key, value in dic.iteritems():
        obj = Dummy()
        setattr(obj, keyattr, key)
        setattr(obj, valueattr, value)
        objs.append(obj)
    return objs

def between(i, b1, b2):
    """ Is `i` between `b1` and `b2`? """
    return (i > b1 and i < b2)

def split_gesture(s):
    """ split gesture by ,; return list of string-tuples """
    l = []
    old = ''
    in_tuple = False
    for char in s:
        if char == '(':
            old += char
            in_tuple = True
        elif char == ')':
            old += char
            in_tuple = False
        elif char == ',' and not in_tuple:
            l.append(old)
            old = ''
        else:
            old += char
    if old:
        l.append(old)
    return l


def gesture2py(s):
    """ Convert a gesture to a python list with tuples """
    l = []
    for tup in split_gesture(s):
        l.append(str2tuple(tup))
    return l

def str2tuple(s):
    """Convert tuple-like strings to real tuples.
    e.g. '(1,2,3,4)' -> (1, 2, 3, 4)

    from http://www.dbforums.com/showpost.php?&p=5469452&postcount=15 - thanks :-)
    """
    if s[0] + s[-1] != "()":
        raise ValueError("Badly formatted string (missing brackets).")
    items = s[1:-1] # removes the leading and trailing brackets
    items = items.split(',')
    L = [int(x.strip()) for x in items] # clean up spaces, convert to ints
    return tuple(L)

def in_range(a, b, shw=60):
    """ Is `a` in range of `b` ?
        @param a: a point (tuple)
        @param b: a point (tuple)
        @param shw: the tolerance value
    """
    dx, dy = a[0] - b[0], a[1] - b[1]
    if abs(dx) > shw or abs(dy) > shw:
        return True
    else:
        return False

def calc_direction(a, b, shw=20):
    """ Calculate direction from pos1 (a) to pos2 (a), return tuple (x,y), e.g. (1,1)
        shw: as higher as more tolerant. recommended: ~ 20 """
    # NEW Method with angles (2007-12-28)
    # http://pics.ubuntu-projekte.de/bild.php/205,winkel2PL7C6.png
    # alpha = arctan(opposite/adjacent)
    # alpha = arctan(gegenkathete/ankathete)
    move_x, move_y = 0,0
    c = (b[0], a[1])
    ac = c[0] - a[0]
    bc = b[1] - c[1]
    alpha = math.degrees(math.atan2(bc, ac))
    #if abs(b[0]-a[0]) > shw and abs(b[1]-a[1]) > shw:
    if in_range(b, a, shw):
        if between(alpha, -15, 15):
            return (1, 0)
        elif between(alpha, 15, 75):
            return (1, 1)
        elif between(alpha, 75, 105):
            return (0, 1)
        elif between(alpha, 105, 165):
            return (-1, 1)
        elif alpha < -165 or alpha > 165:
            return (-1, 0)
        elif between(alpha, -165, -105):
            return (-1, -1)
        elif between(alpha, -105, -75):
            return (0, -1)
        elif between(alpha, -75, -15):
            return (1, -1)
        else:
            return (0,0)
    else:
        return (0,0)


def remove_duplicates(l):
    """ Remove upfollowing duplicates from the list """
    indices = range(len(l)) # list of saved indices
    last_e = None
    for index in range(len(l)):
        e = l[index]
        if e == last_e:
            indices.remove(index)
        last_e = e
    return [l[i] for i in indices]

def dict_rev(d):
    """ return d 'reversed': keys are values, values are keys """
    r = {}
    for k,v in d.iteritems():
        r[v] = k
    return r

def format_action(action):
    """ Format an Action() human-readable """
    return _('Gesture %(gesture)s: %(action)s') % {'gesture':action.gesture, 'action':action.get_formatted()}

def init_gettext():
    """ init gettext """
    gettext.install('gestikk')
    gtk.glade.textdomain('gestikk')
    # first in system's defaults
    try:
        lang = gettext.translation('gestikk', '/usr/share/locale')
        gtk.glade.bindtextdomain('gestikk')
    # then in ./locale/
    except IOError:
        lang = gettext.translation('gestikk', os.path.join(BASEDIR, 'locale'), fallback=True)
        gtk.glade.bindtextdomain('gestikk', os.path.join(BASEDIR, 'locale'))
        # otherwise: fallback (english)
    return lang

def is_gestikk(pid):
    """ Test whether the process with the given pid is gestikk.
        It has to be started with python gestikk.py, gestikk or something similar.
        Works only with Unix/Linux """
    fcmdline = file('/proc/%d/cmdline' % pid, 'r')
    content = fcmdline.read()
    fcmdline.close()
    return 'gestikk' in content

def get_process_by_pid(pid):
    """ get a process name by its pid """
    try:
        f = file('/proc/%d/status' % pid, 'r')
    except IOError:
        return '<could not be recognized>'
    name = '<could not be recognized>'
    while 1:
        line = f.readline().lower()
        if line.startswith('name'):
            name = line[len('name:'):].strip()
            break
    return name

def get_about_dialog():
    """ get the gtk about dialog """
    info = gtk.AboutDialog()
    info.set_name('gestikk')
    logo = gtk.Image()
    logo.set_from_file(get_file("gestikk.png", "pixmap"))
    info.set_logo(logo.get_pixbuf())
    info.set_license(get_gpl())
    info.set_authors(["Friedrich 'fred.reichbier' Weber - development", "Jonas 'Dauerbaustelle' Haag - development", "BigChiller - Packaging"])
    info.set_website("http://gestikk.reichbier.de/")
    translators = TRANSLATORS
    if _('translator-credits') != 'translator-credits':
        translators += '\n' + _('translator-credits')
    info.set_translator_credits(translators)
    info.set_copyright("(C) 2007-2008 Friedrich Weber")
    return info

class Debugger:
    def __init__(self, mode=False):
        self.debug_on = mode

    def debug(self, string):
        if self.debug_on:
            print 'DEBUG:', string


class ActionTemplate():
    """ Template class for writin actions into configuration file """
    def __init__(self, caction, help):
        """ Ident is the Action()
            help is a helptext"""
        self.caction = caction
        self.help = help

class Action():
    """ Action to execute; Prototyp-Class """
    def __init__(self, gesture, condition, parameter):
        """
            :param gesture: The gesture as saveable string, e.g. '(1,0),(-1,1)'
            :param condition: The condition string
            :param parameter: The action parameter
        """
        self.gesture = gesture
        self.condition = condition
        self.parameter = parameter

    def do(self):
        pass

    def check_condition(self):
        """ check condition of gesture """
        if not self.condition:
            return True
        else:
            return condition_handler.check(self.condition)

    def get_formatted(self):
        """ Get description of the action as human-readable string """
        return ''

    action_formatted = property(get_formatted)

class Action_Command(Action):
    """ Aktion: Execute Command """
    def __init__(self, gesture, condition, cmd):
        """
            :param gesture: The gesture as saveable string, e.g. '(1,0),(-1,1)'
            :param condition: The condition string
            :param cmd: Command as a string
        """
        Action.__init__(self, gesture, condition, cmd)
        self.action = 'cmd'
        self.parameter = cmd
        self.condition = condition

    def do(self):
        """ tu es """
        execute(self.parameter)

    def get_formatted(self):
        """ Get description of the action as human-readable string """
        return _('Start application "%s"') % self.parameter

    action_formatted = property(get_formatted)


class Action_Key(Action):
    """ Aktion: Press key """
    def __init__(self, gesture, condition, key):
        """
            :param gesture: The gesture as saveable string, e.g. '(1,0),(-1,1)'
            :param condition: The condition string
            :param key: Key as X-Keysym, eg. 'alt+Left'
        """
        Action.__init__(self, gesture, condition, key)
        self.action = 'key'
        self.parameter = key
        self.condition = condition

    def do(self):
        """ do it with virtkey """
        simulate_keys(keystroke_to_x11(self.parameter))

    def get_formatted(self):
        """ Get description of the action as human-readable string """
        return _('Simulate keystroke "%s"') % self.parameter

    action_formatted = property(get_formatted)

class GestureXMLReader:
    """ gestures.xml Parser Class """
    def __init__(self, xmlfile):
        self.xmlfilename = xmlfile
        self.tree = None
        self.gestures = {} # gesture expr:Action()

    def parse(self):
        """ Parse the XML-File
        """
        self.tree = ETree.parse(self.xmlfilename)
        self.root = self.tree.getroot()
        for node in self.root.getchildren():
            caction = ACTIONS[node.get('action')]
            gesture = node.get('gesture')
            condition = node.get('condition', '')
            if not gesture in self.gestures:
                self.gestures[gesture] = []
            self.gestures[gesture].append(caction(gesture, condition, node.get('parameter')))

        return self.gestures

class GestureXMLWriter:
    """ gestures.xml Writer class """
    def __init__(self, gestures, dest):
        # gesture expr:Action()
        self.dest = dest
        self.gestures = gestures

    def write(self):
        """ write it """
        root = ETree.Element('gestikk')

        for gesture in dict_unzip(self.gestures):
            node = ETree.SubElement(root, 'gesture')
            node.set('gesture', gesture.gesture)
            node.set('action', gesture.action)
            node.set('condition', gesture.condition)
            node.set('parameter', gesture.parameter)

        tree = ETree.ElementTree(root)
        tree.write(self.dest)

class Logic():
    """ class for saving the logic (of gestures and preferences) """
    def __init__(self):
        self._configuration_window = None # placeholder for the configuration window
        # Config Parser
        self.config = ConfigParser.ConfigParser()
        self.config_file = CONFIG_FILE # todo
        self.config.read(self.config_file)
        # Gesture Parser
        if os.path.isfile(GESTURE_FILE):
            self.gestures = GestureXMLReader(GESTURE_FILE).parse() # gesture expr: Action()
        else:
            self.gestures = {}

        self.action_list = {_('Command'):
            ActionTemplate(Action_Command, _('Execute a command (eg. gksu scite)')),
            _('Keypress'):
            ActionTemplate(Action_Key, _('Press a key combination (eg. alt+Left)'))}

        # switcher
        self.gesture_switchers_txt = {_('Left Mouse Button'): 0,
                                _('Middle Mouse Button'): 1,
                                _('Right Mouse Button'): 2,
                                _('Control Button Down'): 3,
                                _('Alt Button Down'): 4,
                                _('Shift Button Down'): 5
                                }
        self.gesture_switchers = ['leftdown', 'middledown', 'rightdown', 'ctrldown', 'altdown', 'shiftdown', 'cmddown', 'metadown']

        self.current_switcher = self.config_get_option('Preferences', 'switcher', 'rightdown')
        self.current_switcher_txt = dict_rev(self.gesture_switchers_txt)[self.gesture_switchers.index(self.current_switcher)]

        self.notifiers = {"0":_("None"), "balloon":_("Balloontip"), "osd":_("OSD")}


    def add_gesture(self, action):
        """ add the gesture """
        if not action.gesture in self.gestures:
            self.gestures[action.gesture] = []
        self.gestures[action.gesture].append(action)

    def config_get_option(self, section, option, default=''):
        """ Fetch option """
        if self.config.has_section(section) and self.config.has_option(section, option):
            return self.config.get(section, option)
        else:
            return default

    def config_set_option(self, section, option, value):
        """ Setze Option, lege ggf. Sektion neu an """
        if not self.config.has_section(section):
            self.config.add_section(section)
        self.config.set(section, option, value)

    def config_write(self):
        """ Write configuration file """
        fp = file(self.config_file, 'w')
        self.config.write(fp)
        fp.close()

    def save_gestures(self):
        """ Write gesture file """
        GestureXMLWriter(self.gestures, GESTURE_FILE).write()

    def reload_gestures(self):
        """ Reload the gesture file """
        if os.path.isfile(GESTURE_FILE):
            self.gestures = GestureXMLReader(GESTURE_FILE).parse() # gesture expr: Action()
        else:
            self.gestures = {}

    def reload_config(self):
        """ Reload configuration file """
        del self.config
        self.config = ConfigParser.ConfigParser()
        self.config_file = CONFIG_FILE # todo
        self.config.read(self.config_file)
        # switcher
        self.current_switcher = self.config_get_option('Preferences', 'switcher', 'rightdown')
        self.current_switcher_txt = dict_rev(self.gesture_switchers_txt)[self.gesture_switchers.index(self.current_switcher)]


class ViewGestureDialog(gtk.Window):
    """ a dialog for viewing a gesture """
    def __init__(self, gesture):
        """ `gesture` is a gestikk gesture tuple list """
        gtk.Window.__init__(self)
        #self.gesture = [(t[0]*100+200, t[1]*100+200) for t in gesture]
        self.gesture = gesture
        self.set_size = True
        self.show()
        # paint
        img = gtk.Image()
        pixmap = gesture_to_pixmap(self.gesture)
        img.set_from_pixmap(pixmap, None)
        self.add(img)
        #img.se(*point9)
        img.show()
        self.realize()



class WNCKHandler():
    """ handle all wnck-Things :-) """
    def __init__(self):
        scr = wnck.screen_get_default()
        self.scr = scr
        self.update()

    def get_all(self):
        """ get a dict with all values """
        return {'activeApplication':self.get_active_app_name(), \
                'activeWorkspace':self.get_active_workspace_number(), \
                'activeWindowTitle':self.get_active_window_title()}
    def update(self):
        """ update. we have to call this everytime we query something """
        pass

    def get_active_app_name(self):
        """ get the active app name through wnck """
        self.update()
        try:
            return get_process_by_pid(self.scr.get_active_window().get_application().get_pid())
        except:
            return NOT_RECOGNIZED

    def get_active_workspace_number(self):
        """ get the active workspace (starting at 1) """
        try:
            return self.scr.get_active_workspace().get_number() + 1
        except:
            return NOT_RECOGNIZED

    def get_active_window_title(self):
        """ get the active window title """
        self.update()
        try:
            return self.scr.get_active_window().get_name()
        except:
            return NOT_RECOGNIZED


wnck_handler = WNCKHandler()
condition_handler = condition_handler_setup(wnck_handler)
ACTIONS = {'cmd':Action_Command, 'key':Action_Key}
_ = init_gettext().gettext
NOT_RECOGNIZED = _('could not be recognized')