summaryrefslogtreecommitdiff
path: root/src/sardana/taurus/qt/qtgui/extra_sardana/controllertree.py
blob: ed38336b8a7a8db1f96932fba8be617b46b8be5f (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
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
#!/usr/bin/env python

##############################################################################
##
## This file is part of Sardana
##
## http://www.sardana-controls.org/
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
## Sardana 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, either version 3 of the License, or
## (at your option) any later version.
##
## Sardana 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 Sardana.  If not, see <http://www.gnu.org/licenses/>.
##
##############################################################################

"""This module contains a taurus text editor widget."""

__all__ = ["ControllerClassTreeWidget", "ControllerClassSelectionDialog"]

__docformat__ = 'restructuredtext'

import sys
import os

import taurus.core
from taurus.core.util.enumeration import Enumeration
from taurus.external.qt import Qt
from taurus.qt.qtcore.mimetypes import TAURUS_MODEL_MIME_TYPE, TAURUS_MODEL_LIST_MIME_TYPE
from taurus.qt.qtcore.model import TaurusBaseTreeItem, TaurusBaseModel, TaurusBaseProxyModel
from taurus.qt.qtgui.tree import TaurusBaseTreeWidget
from taurus.qt.qtgui.resource import getThemeIcon, getIcon

PoolControllerView = Enumeration("PoolControllerView", ("ControllerModule", "ControllerClass", "Unknown"))

def getElementTypeIcon(t):
    if t == PoolControllerView.ControllerModule:
        return getIcon(":/python-file.png")
    elif t == PoolControllerView.ControllerClass:
        return getIcon(":/python.png")
    return getIcon(":/tango.png")

def getElementTypeSize(t):
    return Qt.QSize(200, 24)

def getElementTypeToolTip(t):
    """Wrapper to prevent loading qtgui when this module is imported"""
    if t == PoolControllerView.ControllerModule:
        return "Controller module"
    elif t == PoolControllerView.ControllerClass:
        return "Controller class"


class ControllerBaseTreeItem(TaurusBaseTreeItem):
    """A generic node"""

    def data(self, index):
        """Returns the data of this node for the given index
        
        :return: (object) the data for the given index
        """
        return self._itemData

    def role(self):
        """Returns the prefered role for the item.
        This implementation returns taurus.core.taurusbasetypes.TaurusElementType.Unknown
        
        This method should be able to return any kind of python object as long
        as the model that is used is compatible.
        
        :return: (PoolControllerView) the role in form of element type"""
        return PoolControllerView.Unknown


class ControllerModuleTreeItem(ControllerBaseTreeItem):

    def role(self):
        return PoolControllerView.ControllerModule

    def toolTip(self):
        return "The controller module '%s'" % self.display()

    def icon(self):
        return getIcon(":/python-file.png")


class ControllerTreeItem(ControllerBaseTreeItem):

    def data(self, index):
        """Returns the data of this node for the given index
        
        :return: (object) the data for the given index
        """
        return self._itemData.name

    def role(self):
        return PoolControllerView.ControllerClass

    def toolTip(self):
        return self._itemData.doc

    def icon(self):
        return getIcon(":/python.png")


class ControllerBaseModel(TaurusBaseModel):

    ColumnNames = "Controllers",
    ColumnRoles = (PoolControllerView.ControllerModule, PoolControllerView.ControllerModule, PoolControllerView.ControllerClass),

    def setDataSource(self, pool):
        if self._data_src is not None:
            Qt.QObject.disconnect(self._data_src, Qt.SIGNAL('controllerClassesUpdated'), self.controllerClassesUpdated)
        if pool is not None:
            Qt.QObject.connect(pool, Qt.SIGNAL('controllerClassesUpdated'), self.controllerClassesUpdated)
        TaurusBaseModel.setDataSource(self, pool)

    def controllerClassesUpdated(self):
        self.refresh()

    def createNewRootItem(self):
        return ControllerBaseTreeItem(self, self.ColumnNames)

    def roleIcon(self, role):
        return getElementTypeIcon(role)

    def columnIcon(self, column):
        return self.roleIcon(self.role(column))

    def roleToolTip(self, role):
        return getElementTypeToolTip(role)

    def columnToolTip(self, column):
        return self.roleToolTip(self.role(column))

    def roleSize(self, role):
        return getElementTypeSize(role)

    def columnSize(self, column):
        role = self.role(column)
        s = self.roleSize(role)
        return s

    def mimeTypes(self):
        return ["text/plain", TAURUS_MODEL_LIST_MIME_TYPE, TAURUS_MODEL_MIME_TYPE]

    def mimeData(self, indexes):
        ret = Qt.QMimeData()
        data = []
        for index in indexes:
            if not index.isValid(): continue
            tree_item = index.internalPointer()
            mime_data_item = tree_item.mimeData(index)
            if mime_data_item is None:
                continue
            data.append(mime_data_item)
        ret.setData(TAURUS_MODEL_LIST_MIME_TYPE, "\r\n".join(data))
        ret.setText(", ".join(data))
        if len(data) == 1:
            ret.setData(TAURUS_MODEL_MIME_TYPE, str(data[0]))
        return ret

    def pyData(self, index, role):
        if not index.isValid():
            return None

        item = index.internalPointer()
        row, column, depth = index.row(), index.column(), item.depth()
        item_role = self.role(column, depth)

        ret = None
        if role == Qt.Qt.DisplayRole:
            ret = Qt.QString(item.data(index))
        elif role == Qt.Qt.DecorationRole:
            ret = item.icon()
        elif role == Qt.Qt.ToolTipRole:
            ret = item.toolTip()
        #elif role == Qt.Qt.SizeHintRole:
        #    ret = self.columnSize(column)
        elif role == Qt.Qt.FontRole:
            ret = self.DftFont
        return ret

    def setupModelData(self, data):
        pool = self.dataSource()
        if pool is None:
            return
        root = self._rootItem
        ctrl_modules = {}
        # TODO
        #ctrl_class_dict = pool.getControllerClasses()
        #for ctrl_class_name, ctrl_class in ctrl_class_dict.items():
        #    module_name = ctrl_class.module_name
        #    moduleNode = ctrl_modules.get(module_name)
        #    if moduleNode is None:
        #        moduleNode = ControllerModuleTreeItem(self, module_name, root)
        #        root.appendChild(moduleNode)
        #        ctrl_modules[module_name] = moduleNode
        #    ctrlNode = ControllerTreeItem(self, ctrl_class, moduleNode)
        #    moduleNode.appendChild(ctrlNode)


class ControllerModuleModel(ControllerBaseModel):
    pass


class PlainControllerModel(ControllerBaseModel):

    ColumnNames = "Controller classes",
    ColumnRoles = (PoolControllerView.ControllerClass, PoolControllerView.ControllerClass),

    def setupModelData(self, data):
        pool = self.dataSource()
        if pool is None:
            return
        root = self._rootItem
        # TODO
        #ctrl_class_dict = pool.getControllerClasses()
        #ctrl_classes = ctrl_class_dict.keys()
        #ctrl_classes.sort()
        #self.debug("Found %d controller classes", len(ctrl_classes))
        #for ctrl_class_name in ctrl_classes:
        #    ctrl_class = ctrl_class_dict[ctrl_class_name]
        #    ctrlNode = ControllerTreeItem(self, ctrl_class, root)
        #    root.appendChild(ctrlNode)


class ControllerBaseModelProxy(TaurusBaseProxyModel):
    pass


class ControllerModuleModelProxy(ControllerBaseModelProxy):
    pass


class PlainControllerModelProxy(ControllerBaseModelProxy):
    pass


class ControllerClassTreeWidget(TaurusBaseTreeWidget):

    KnownPerspectives = { PoolControllerView.ControllerModule : {
                            "label" : "By module",
                            "icon" : ":/python-file.png",
                            "tooltip" : "View by controller module",
                            "model" : [ControllerModuleModelProxy, ControllerModuleModel],
                          },
                          PoolControllerView.ControllerClass : {
                            "label" : "By controller",
                            "icon" : ":/python.png",
                            "tooltip" : "View by controller class",
                            "model" : [PlainControllerModelProxy, PlainControllerModel],
                          }
    }
    DftPerspective = PoolControllerView.ControllerModule

    def getModelClass(self):
        return taurus.core.taurusdevice.TaurusDevice


class ControllerClassSelectionDialog(Qt.QDialog):

    def __init__(self, parent=None, designMode=False, model_name=None, perspective=None):
        Qt.QDialog.__init__(self, parent)

        self.setWindowTitle("Controller Class Selection Dialog")

        layout = Qt.QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        self._panel = ControllerClassTreeWidget(parent=self,
                                                perspective=perspective,
                                                designMode=designMode,
                                                with_navigation_bar=False)
        self._panel.setModel(model_name)
        self.setWindowIcon(getElementTypeIcon(self._panel.perspective()))
        self._buttonBox = Qt.QDialogButtonBox(self)
        bts = Qt.QDialogButtonBox.Ok | Qt.QDialogButtonBox.Cancel
        self._buttonBox.setStandardButtons(bts)
        layout.addWidget(self._panel)
        layout.addWidget(self._buttonBox)
        self.connect(self._buttonBox, Qt.SIGNAL("accepted()"), self.accept)
        self.connect(self._buttonBox, Qt.SIGNAL("rejected()"), self.reject)

    def selectedItems(self):
        return self._panel.selectedItems()

    def getSelectedMacros(self):
        return [ i.itemData() for i in self.selectedItems() ]


def main_ControllerClassSelecionDialog(pool, perspective=PoolControllerView.ControllerClass):
    w = ControllerClassSelectionDialog(model_name=pool, perspective=perspective)

    if w.result() == Qt.QDialog.Accepted:
        print w.getSelectedMacros()
    return w

def main_ControllerClassTreeWidget(pool, perspective=PoolControllerView.ControllerClass):
    w = ControllerClassTreeWidget(perspective=perspective, with_navigation_bar=False)
    w.setModel(pool)
    w.show()
    return w

def demo(poolname="Pool_BL98"):
    """ControllerClassTreeWidget"""
    w = main_ControllerClassSelecionDialog(poolname, PoolControllerView.ControllerClass)
    return w

def main():
    import sys
    import taurus.qt.qtgui.application
    Application = taurus.qt.qtgui.application.TaurusApplication

    app = Application.instance()
    owns_app = app is None

    if owns_app:
        app = Application(app_name="Pool controller class tree demo", app_version="1.0",
                          org_domain="Taurus", org_name="Tango community")

    args = app.get_command_line_args()
    if len(args) == 1:
        w = demo(poolname=args[0])
    else:
        w = demo()

    w.show()
    if owns_app:
        sys.exit(app.exec_())
    else:
        return w

if __name__ == "__main__":
    main()