~javier.collado/bugtimetracker/trunk

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
"""
GTK customized widgets and wrappers module
"""
import os
from collections import defaultdict

from gi.repository import Gtk


class UIFile(object):
    def __init__(self, ui_file):
        # It's assumed that ui_file is located under ui directory
        # relative to source file path
        ui_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                               'ui', ui_file)

        builder = Gtk.Builder()
        builder.add_from_file(ui_file)
        builder.connect_signals(self)
        self.builder = builder

        # Keep a record of all handlers to disconnect them later if needed
        self._handler_ids = defaultdict(list)

    def __getattr__(self, name):
        """
        Look for widgets in builder object as attributes
        """
        obj = self.builder.get_object(name)

        if obj is None:
            raise AttributeError(name)

        return obj

    def connect(self, obj, signal, handler, *args):
        """
        Connect signal handler and keep a record of its id
        to disconnect it on destroy
        """
        handler_id = obj.connect(signal, handler, *args)
        self._handler_ids[obj].append(handler_id)

    def disconnect_all(self):
        """
        Disconnect all handlers
        """
        for obj, handler_ids in self._handler_ids.iteritems():
            for handler_id in handler_ids:
                if obj.handler_is_connected(handler_id):
                    obj.disconnect(handler_id)


class Image(Gtk.Image):
    """
    `Gtk.Image` wrapper to set the file name easily
    """
    def __init__(self, img_basename):
        """
        Initialize image and set contents to filename
        """
        super(Image, self).__init__()

        # It's assumed that image file is located under ui/img directory
        # relative to source file path
        img_filename = \
                os.path.join(os.path.dirname(os.path.realpath(__file__)),
                             'ui', 'img', img_basename)
        self.set_from_file(img_filename)