aboutsummaryrefslogtreecommitdiff
path: root/tests/script/menuscript.py
blob: db71c084865570a83d9da8d5f41d13a5768d4828 (plain)
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
#  Copyright 2013 Canonical Ltd.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; version 3.
#
#  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 Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import dbus
import dbus.service
from dbus import glib
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GObject
from gi.repository import GLib
from gi.repository import Gio

SERVICE_NAME     = "com.canonical.test"
INTERFACE_NAME   = "com.canonical.test.menuscript"
OBJECT_PATH      = "/com/canonical/test/menuscript"
MENU_SERVICE_NAME= SERVICE_NAME + ".menu"
MENU_OBJECT_PATH = OBJECT_PATH + "/menu"
bus = None

class Script(dbus.service.Object):
    def __init__(self, aList, session, object_path):
        dbus.service.Object.__init__(self, session, object_path)
        self._list = aList
        self._session  = session

    def run(self):
        self._loop = GObject.MainLoop()
        self._loop.run()

    @dbus.service.method(dbus_interface=INTERFACE_NAME,
                         in_signature='', out_signature='',
                         sender_keyword='sender')
    def publishMenu(self, sender=None):
        self._list.start()

    @dbus.service.method(dbus_interface=INTERFACE_NAME,
                         in_signature='', out_signature='',
                         sender_keyword='sender')
    def unpublishMenu(self, sender=None):
        self._list.stop()

    @dbus.service.method(dbus_interface=INTERFACE_NAME,
                         in_signature='', out_signature='',
                         sender_keyword='sender')
    def quit(self, sender=None):
        self.unpublishMenu();
        self._loop.quit()

    @dbus.service.method(dbus_interface=INTERFACE_NAME,
                         in_signature='i', out_signature='',
                         sender_keyword='sender')
    def walk(self, steps, sender=None):
        if steps == -1 or steps > self._list.size():
            steps = self._list.size()

        while(steps > 0):
            self._list.walk()
            steps -= 1

    """ TODO: We only support string states for now """
    @dbus.service.method(dbus_interface=INTERFACE_NAME,
                         in_signature='', out_signature='ss')
    def popActivatedAction(self):
        return self._list._activatedActions.pop(0)

    @staticmethod
    def create(aList):
        global bus

        GObject.threads_init()
        glib.threads_init()

        dbus_loop = DBusGMainLoop()
        bus = dbus.SessionBus(mainloop=dbus_loop)
        bus_name = dbus.service.BusName(SERVICE_NAME, bus=bus)
        return Script(aList, bus_name, OBJECT_PATH)

class Action(object):
    def __init__(self, aList, action, **kwargs):
        self._list = aList
        self._action = action
        self._kargs = kwargs

    def setProperties(self, menu, props):
        if props:
           for key in props:
               menu.set_attribute_value(key, props[key])

    def appendItem(self):
        parentId = self._kargs['parentId']
        if parentId and len(parentId):
            parent = self._list.getMenu(parentId)[0]
        else:
            parent = self._list._root

        if self._kargs['link'] == None:
            item = Gio.MenuItem.new(self._kargs['label'], self._kargs['actionName'])
            self.setProperties(item, self._kargs['properties'])
            parent.append_item(item)

            # Action
            act = Gio.SimpleAction.new(self._kargs['actionName'], self._kargs['actionStateType'])
            act.connect('activate', self._list._onActionActivated)
            self._list._rootAction.insert(act)

        elif self._kargs['link'] == 'section':
            section = Gio.Menu()
            parent.append_section(self._kargs['label'], section)
        elif self._kargs['link'] == 'submenu':
            submenu = Gio.Menu()
            parent.append_submenu(self._kargs['label'], submenu)

    def removeItem(self):
        menuId = self._kargs['menuId']
        (menu, mId) = self._list.getMenu(menuId)
        if mId != -1:
            menu.remove(mId)
            if self._kargs['actionName']:
                # Remove action
                self._list._rootAction.remove(self._kargs['actionName'])
        else:
            print("Remove menu item")

    def run(self):
        if self._action == 'append':
            self.appendItem()
        elif self._action == 'remove':
            self.removeItem()

class ActionList(object):
    def __init__(self, objectPath):
        self._actions = []
        self._actions_bk = []
        self._objectPath = objectPath
        self._bus = None
        self._exportMenuID = None
        self._exportActionID = None
        self._ownNameID = None
        self._root = None
        self._rootAction = None
        self._activatedActions = []

    def appendItem(self, label, actionName, link=None, parentId=None,  properties=None, actionStateType=None):
        self._actions.append(Action(self, 'append',
                                    parentId=parentId,
                                    label=label,
                                    actionName=actionName,
                                    link=link,
                                    properties=properties,
                                    actionStateType=actionStateType))

    def removeItem(self, menuId, actionName=None):
        self._actions.append(Action(self, 'remove',
                                    menuId=menuId,
                                    actionName=actionName))

    def _save(self):
        self._actions_bk = []
        self._actions_bk.extend(self._actions)


    def _restore(self):
        if len(self._actions_bk):
            self._actions = []
            self._actions.extend(self._actions_bk)

    def _findMenu(self, root, ids):
        if len(ids) == 0:
            return (root, -1)

        currentId = int(ids[0])
        link = root.get_item_link(currentId, 'section')
        if link == None:
            link = root.get_item_link(currentId, 'submenu')

        if link:
            return self._findMenu(link, ids[1:])
        else:
            return (root, currentId)

    def getMenu(self, menuId):
        return self._findMenu(self._root, str(menuId).split('.'));

    def walk(self):
        item = self._actions.pop(0)
        item.run()

    def size(self):
        return len(self._actions)

    def _exportService(self, connection, name):
        self._root = Gio.Menu()
        self._rootAction = Gio.SimpleActionGroup()
        self._bus = connection
        self._exportMenuID = connection.export_menu_model(MENU_OBJECT_PATH, self._root)
        self._exportActionID = connection.export_action_group(MENU_OBJECT_PATH, self._rootAction)

    def start(self):
        self._save()
        self._ownNameID = Gio.bus_own_name(2, MENU_SERVICE_NAME, 0, self._exportService, None, None)

    def stop(self):
        if self._exportMenuID:
            self._bus.unexport_menu_model(self._exportMenuID)
            self._exportMenuID = None

        if self._exportActionID:
            self._bus.unexport_action_group(self._exportActionID)
            self._exportActionID = None

        if self._ownNameID:
            Gio.bus_unown_name(self._ownNameID)
            self._ownNameID = None

        self._root = None
        self._rootAction = None
        self._restore()

    def _onActionActivated(self, action, parameter):
        self._activatedActions.append((action.get_name(), parameter.get_string()))