This repository has been archived by the owner on Mar 17, 2021. It is now read-only.
/
taurusgui.py
1857 lines (1605 loc) · 76.5 KB
/
taurusgui.py
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#############################################################################
##
# This file is part of Taurus
##
# http://taurus-scada.org
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Taurus 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.
##
# Taurus 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 Taurus. If not, see <http://www.gnu.org/licenses/>.
##
###########################################################################
"""This package provides the TaurusGui class"""
from __future__ import absolute_import
from builtins import str
import os
import sys
import copy
import click
import weakref
import inspect
from future.utils import string_types
from lxml import etree
import taurus
from taurus import tauruscustomsettings
from taurus.external.qt import Qt, compat
from taurus.qt.qtcore.configuration import BaseConfigurableClass
from taurus.qt.qtcore.communication import SharedDataManager
from taurus.qt.qtgui.util import TaurusWidgetFactory
from taurus.qt.qtgui.base import TaurusBaseWidget, TaurusBaseComponent
from taurus.qt.qtgui.container import TaurusMainWindow
from taurus.qt.qtgui.taurusgui.utils import (ExternalApp, PanelDescription,
ToolBarDescription,
AppletDescription)
from taurus.qt.qtgui.util.ui import UILoadable
from taurus.qt.qtgui.taurusgui.utils import ExternalAppAction
from taurus.core.util.log import deprecation_decorator
__all__ = ["DockWidgetPanel", "TaurusGui"]
__docformat__ = 'restructuredtext'
@UILoadable(with_ui='ui')
class AssociationDialog(Qt.QDialog):
'''A dialog for viewing and editing the associations between instruments
and panels'''
def __init__(self, parent, flags=None):
if flags is None:
flags = Qt.Qt.Widget
Qt.QDialog.__init__(self, parent, flags)
self.loadUi()
self.refresh()
self.ui.instrumentCB.activated.connect(self.onInstrumentChanged)
self.ui.buttonBox.clicked.connect(self.onDialogButtonClicked)
self.ui.refreshBT.clicked.connect(self.refresh)
def refresh(self):
currentinstrument = self.ui.instrumentCB.currentText()
mainwindow = self.parent()
self.associations = mainwindow.getAllInstrumentAssociations()
# fill the comboboxes
self.ui.instrumentCB.clear()
self.ui.panelCB.clear()
self.ui.instrumentCB.addItems(sorted(self.associations.keys()))
self.ui.panelCB.addItems(['__[None]__'] + mainwindow.getPanelNames())
# restore the index
idx = self.ui.instrumentCB.findText(currentinstrument)
if idx == -1 and self.ui.instrumentCB.count() > 0:
idx = 0
self.ui.instrumentCB.setCurrentIndex(idx)
self.onInstrumentChanged(self.ui.instrumentCB.currentText())
def onInstrumentChanged(self, instrumentname):
instrumentname = str(instrumentname)
panelname = self.associations.get(instrumentname)
if panelname is None:
self.ui.panelCB.setCurrentIndex(0)
return
else:
idx = self.ui.panelCB.findText(panelname)
self.ui.panelCB.setCurrentIndex(idx)
def onDialogButtonClicked(self, button):
role = self.ui.buttonBox.buttonRole(button)
if role in (Qt.QDialogButtonBox.AcceptRole, Qt.QDialogButtonBox.ApplyRole):
if self.ui.panelCB.currentIndex() > 0:
panelname = str(self.ui.panelCB.currentText())
else:
panelname = None
instrumentname = str(self.ui.instrumentCB.currentText())
self.associations[instrumentname] = panelname
self.parent().setInstrumentAssociation(instrumentname, panelname)
class DockWidgetPanel(Qt.QDockWidget, TaurusBaseWidget):
'''
This is an extended QDockWidget which provides some methods for being used
as a "panel" of a TaurusGui application. Widgets of TaurusGui are inserted
in the application by adding them to a DockWidgetPanel.
'''
def __init__(self, parent, widget, name, mainwindow):
Qt.QDockWidget.__init__(self, None)
TaurusBaseWidget.__init__(self, name, parent=parent)
self.setAllowedAreas(Qt.Qt.TopDockWidgetArea)
self.setWidget(widget)
# self._widget = self.widget() #keep a pointer that may change if the
# widget changes
name = str(name)
self.setWindowTitle(name)
self.setObjectName(name)
self._custom = False
# store a weakref of the main window
self._mainwindow = weakref.proxy(mainwindow)
def isCustom(self):
return self._custom
def setCustom(self, custom):
self._custom = custom
def isPermanent(self):
return self._permanent
def setPermanent(self, permanent):
self._permanent = permanent
def setWidgetFromClassName(self, classname, modulename=None):
if self.getWidgetClassName() != classname:
try:
klass = TaurusWidgetFactory().getWidgetClass(classname)
w = klass()
except:
try:
if classname is not None and '.' in classname:
mn, classname = classname.rsplit('.', 1)
modulename = ("%s.%s" %
(modulename or '', mn)).strip('. ')
module = __import__(modulename, fromlist=[''])
klass = getattr(module, classname)
w = klass()
except Exception as e:
raise RuntimeError(
'Cannot create widget from classname "%s". Reason: %s' % (classname, repr(e)))
# ----------------------------------------------------------------
# Backwards-compat. Remove when removing CW map support
gui_cwmap = self._mainwindow._customWidgetMap
if gui_cwmap and hasattr(w, 'setCustomWidgetMap'):
w.setCustomWidgetMap(gui_cwmap)
# ----------------------------------------------------------------
self.setWidget(w)
wname = "%s-%s" % (str(self.objectName()), str(classname))
w.setObjectName(wname)
def getWidgetModuleName(self):
w = self.widget()
if w is None:
return ''
return w.__module__
def getWidgetClassName(self):
w = self.widget()
if w is None:
return ''
return w.__class__.__name__
def applyConfig(self, configdict, depth=-1):
# create the widget
try:
self.setWidgetFromClassName(configdict.get(
'widgetClassName'), modulename=configdict.get('widgetModuleName', None))
if isinstance(self.widget(), BaseConfigurableClass):
self.widget().applyConfig(configdict['widget'])
except Exception as e:
self.info(
'Failed to set the widget for this panel. Reason: %s' % repr(e))
self.traceback(self.Debug)
return
TaurusBaseWidget.applyConfig(self, configdict, depth)
def createConfig(self, *args, **kwargs):
configdict = TaurusBaseWidget.createConfig(self, *args, **kwargs)
configdict['widgetClassName'] = self.getWidgetClassName()
configdict['widgetModuleName'] = self.getWidgetModuleName()
if isinstance(self.widget(), BaseConfigurableClass):
configdict['widget'] = self.widget().createConfig()
return configdict
def closeEvent(self, event):
Qt.QDockWidget.closeEvent(self, event)
TaurusBaseWidget.closeEvent(self, event)
class TaurusGui(TaurusMainWindow):
"""
This is main class for constructing the dynamic GUIs. TaurusGui is a
specialised TaurusMainWindow which is able to handle "panels" and load
configuration files.
There are several ways of using TaurusGui. In the following we will give
3 examples on how to create a simple GUI called "MyGui" which contains one
panel called "Foo" and consisting of a `QWidget`:
**Example 1: use declarative configuration files.**
You can create a purely declarative configuration file to be interpreted by
the standard `taurusgui` script::
from taurus.qt.qtgui.taurusgui.utils import PanelDescription
GUI_NAME = 'MyGui'
panel = PanelDescription('Foo',
classname='taurus.external.qt.Qt.QWidget')
Note that this just a very simple example. For a much richer one, see the
:mod:`taurus.qt.qtgui.taurusgui.conf.tgconf_example01`
**Example 2: do everything programmatically.**
A stand-alone python script that launches the gui when executed. No
configuration file is used here. Panels and other components are added
programatically::
if __name__ == '__main__':
from taurus.qt.qtgui.application import TaurusApplication
from taurus.qt.qtgui.taurusgui import TaurusGui
from taurus.external.qt import Qt
app = TaurusApplication(cmd_line_parser=None, app_name='MyGui')
gui = TaurusGui()
panel = Qt.QWidget()
gui.createPanel(panel, 'Foo')
gui.show()
app.exec_()
**Example 3: mixing declarative and programmatic ways**
It is also possible to create a stand-alone python script which loads itself
as a configuration file. In this way you can add things programmatically and
at the same time use the declarative way::
GUI_NAME = 'MyGui' # <-- declarative!
if __name__ == '__main__':
from taurus.qt.qtgui.application import TaurusApplication
from taurus.qt.qtgui.taurusgui import TaurusGui
from taurus.external.qt import Qt
app = TaurusApplication(cmd_line_parser=None)
gui = TaurusGui(confname=__file__)
panel = Qt.QWidget()
gui.createPanel(panel, 'Foo') # <-- programmatic!
gui.show()
app.exec_()
"""
SelectedInstrument = Qt.pyqtSignal('QString')
doorNameChanged = Qt.pyqtSignal('QString')
macroserverNameChanged = Qt.pyqtSignal('QString')
newShortMessage = Qt.pyqtSignal('QString')
IMPLICIT_ASSOCIATION = '__[IMPLICIT]__'
#: Whether to show user actions related to shared data connections
PANELS_MENU_ENABLED = True
#: Whether to show the applets toolbar
APPLETS_TOOLBAR_ENABLED = True
#: wether to add the Quick access Toolbar (empty by default)
QUICK_ACCESS_TOOLBAR_ENABLED = True
def __init__(self, parent=None, confname=None, configRecursionDepth=None,
settingsname=None):
TaurusMainWindow.__init__(self, parent, False, True)
if configRecursionDepth is not None:
self.defaultConfigRecursionDepth = configRecursionDepth
self.__panels = {}
self.__external_app = {}
self.__external_app_actions = {}
self._external_app_names = []
self.__permanent_ext_apps = []
self.__synoptics = []
self.__instrumentToPanelMap = {}
self.__panelToInstrumentMap = {}
self.setDockNestingEnabled(True)
self.registerConfigProperty(self._getPermanentExternalApps,
self._setPermanentExternalApps,
'permanentexternalapps')
self.registerConfigProperty(
self._getPermanentCustomPanels, self._setPermanentCustomPanels, 'permanentCustomPanels')
self.registerConfigProperty(self.getAllInstrumentAssociations,
self.setAllInstrumentAssociations, 'instrumentAssociation')
# backwards-compat
from taurus import tauruscustomsettings
cwmap = getattr(tauruscustomsettings, 'T_FORM_CUSTOM_WIDGET_MAP', {})
self._customWidgetMap = cwmap # deprecated
# Create a global SharedDataManager
Qt.qApp.SDM = SharedDataManager(self)
# Initialize menus & toolbars
if self.PANELS_MENU_ENABLED:
self.__initPanelsMenu()
self.__initPanelsToolBar()
if self.QUICK_ACCESS_TOOLBAR_ENABLED:
self.__initQuickAccessToolBar()
if self.APPLETS_TOOLBAR_ENABLED:
self.__initJorgBar()
self.__initSharedDataConnections()
if self.TOOLS_MENU_ENABLED:
self.__initToolsMenu()
# Create lockview actions
self._lockviewAction = Qt.QAction(Qt.QIcon.fromTheme(
"system-lock-screen"), "Lock View", self)
self._lockviewAction.setCheckable(True)
self._lockviewAction.toggled.connect(self.setLockView)
self._lockviewAction.setChecked(not self.isModifiableByUser())
if self.VIEW_MENU_ENABLED:
self.__initViewMenu()
if settingsname:
self.resetQSettings()
_s = Qt.QSettings(settingsname, Qt.QSettings.IniFormat)
self.setQSettings(_s)
self.loadConfiguration(confname)
# connect the main window itself as a reader/writer of "short messages"
Qt.qApp.SDM.connectReader("shortMessage", self.onShortMessage)
Qt.qApp.SDM.connectWriter("shortMessage", self, 'newShortMessage')
# emit a short message informing that we are ready to go
msg = '%s is ready' % Qt.qApp.applicationName()
self.newShortMessage.emit(msg)
if self.defaultConfigRecursionDepth >= 0:
self.newShortMessage.emit(
"Running in Safe Mode. Settings not loaded"
)
self.warning(
"Safe mode: \n"
+ '\n\tLoading of potentially problematic settings is disabled.'
+ '\n\tSome panels may not be loaded or may ignore previous '
+ 'user configuration'
+ '\n\tThis will also apply when loading perspectives'
)
def closeEvent(self, event):
try:
self.__macroBroker.removeTemporaryPanels()
except:
pass
TaurusMainWindow.closeEvent(self, event)
for n, panel in self.__panels.items():
panel.closeEvent(event)
panel.widget().closeEvent(event)
if not event.isAccepted():
result = Qt.QMessageBox.question(
self, 'Closing error',
"Panel '%s' cannot be closed. Proceed closing?" % n,
Qt.QMessageBox.Yes | Qt.QMessageBox.No)
if result == Qt.QMessageBox.Yes:
event.accept()
else:
break
def __updatePanelsMenu(self):
'''dynamically fill the panels menus'''
panelsmenu = self.sender()
permanent = (panelsmenu == self.__permPanelsMenu)
panelsmenu.clear()
panelnames = sorted(
[n for n, p in self.__panels.items() if (p.isPermanent() == permanent)])
for name in panelnames:
panelsmenu.addAction(self.__panels[name].toggleViewAction())
def __initPanelsMenu(self):
# Panels menu
self.__panelsMenu = Qt.QMenu('Panels', self)
try: # insert the panels menu before the help menu
self.menuBar().insertMenu(self.helpMenu.menuAction(),
self.__panelsMenu)
except AttributeError: # Or just add it if help menu is not shown
self.menuBar().addMenu(self.__panelsMenu)
self.hideAllPanelsAction = self.__panelsMenu.addAction(
Qt.QIcon('actions:hide.svg'), "Hide all panels", self.hideAllPanels)
self.showAllPanelsAction = self.__panelsMenu.addAction(
Qt.QIcon('actions:show.svg'), "Show all panels", self.showAllPanels)
self.newPanelAction = self.__panelsMenu.addAction(
Qt.QIcon.fromTheme("window-new"), "New Panel...",
self.createCustomPanel)
self.removePanelAction = self.__panelsMenu.addAction(
Qt.QIcon.fromTheme("edit-clear"), "Remove Panel...",
self.removePanel)
self.__panelsMenu.addAction(Qt.QIcon.fromTheme(
"preferences-desktop-personal"),
"Switch temporary/permanent status...",
self.updatePermanentCustomPanels)
# temporary and permanent panels submenus
self.__panelsMenu.addSeparator()
self.__permPanelsMenu = Qt.QMenu('Permanent Panels', self)
self.__panelsMenu.addMenu(self.__permPanelsMenu)
self.__permPanelsMenu.aboutToShow.connect(self.__updatePanelsMenu)
self.__tempPanelsMenu = Qt.QMenu('Temporary Panels', self)
self.__panelsMenu.addMenu(self.__tempPanelsMenu)
self.__tempPanelsMenu.aboutToShow.connect(self.__updatePanelsMenu)
self.__panelsMenu.addSeparator()
def __initViewMenu(self):
# the superclass may already have added stuff to the viewMenu
self.viewMenu.addSeparator()
# view locking
self.viewMenu.addSeparator()
self.viewMenu.addAction(self._lockviewAction)
def __initPanelsToolBar(self):
# Panels toolbar
self.panelsToolBar = self.addToolBar("Panels")
self.panelsToolBar.setObjectName("PanelsToolbar")
self.panelsToolBar.addAction(self.newPanelAction)
if self.VIEW_MENU_ENABLED:
self.viewToolBarsMenu.addAction(self.panelsToolBar.toggleViewAction())
def __initQuickAccessToolBar(self):
self.quickAccessToolBar = self.addToolBar("Quick Access")
self.quickAccessToolBar.setObjectName("quickAccessToolbar")
self.quickAccessToolBar.setToolButtonStyle(
Qt.Qt.ToolButtonTextBesideIcon)
if self.VIEW_MENU_ENABLED:
self.viewToolBarsMenu.addAction(
self.quickAccessToolBar.toggleViewAction()
)
def __initJorgBar(self):
# Fancy Stuff ToolBar (aka Jorg's Bar ;) )
self.jorgsBar = Qt.QToolBar('Fancy ToolBar')
self.jorgsBar.setObjectName('jorgsToolBar')
self.addToolBar(Qt.Qt.RightToolBarArea, self.jorgsBar)
self.jorgsBar.setIconSize(Qt.QSize(60, 60))
self.jorgsBar.setMovable(False)
def __initSharedDataConnections(self):
# register the TAURUSGUI itself as a writer/reader for several shared
# data items
splashScreen = self.splashScreen()
if splashScreen is not None:
self.splashScreen().showMessage("setting up shared data connections")
Qt.qApp.SDM.connectWriter(
"macroserverName", self, 'macroserverNameChanged')
Qt.qApp.SDM.connectWriter("doorName", self, 'doorNameChanged')
Qt.qApp.SDM.connectReader(
"SelectedInstrument", self.onSelectedInstrument)
Qt.qApp.SDM.connectWriter(
"SelectedInstrument", self, 'SelectedInstrument')
Qt.qApp.SDM.connectReader("executionStarted", self.setFocusToPanel)
Qt.qApp.SDM.connectReader("selectedPerspective", self.loadPerspective)
Qt.qApp.SDM.connectWriter(
"perspectiveChanged", self, 'perspectiveChanged')
def __initToolsMenu(self):
if self.toolsMenu is None:
self.toolsMenu = Qt.QMenu("Tools")
tm = self.toolsMenu
tm.addAction(Qt.QIcon("apps:preferences-system-session.svg"),
"manage instrument-panel associations", self.onShowAssociationDialog)
tm.addAction(Qt.QIcon.fromTheme("document-save"),
"Export current Panel configuration to XML",
self.onExportCurrentPanelConfiguration)
tm.addAction(Qt.QIcon("actions:data-transfer.svg"),
"Show Shared Data Manager connections", self.showSDMInfo)
# tools->external apps submenu
self.addExternalApplicationAction = self.externalAppsMenu.addAction(
Qt.QIcon.fromTheme('list-add'),
'Add external application launcher...',
self.createExternalApp)
self.removeExternalApplicationAction = self.externalAppsMenu.addAction(
Qt.QIcon.fromTheme('list-remove'),
'Remove external appication launcher...',
self.removeExternalApp)
self.externalAppsMenu.addSeparator()
def createExternalApp(self):
'''Add a new external application on execution time'''
from .appsettingswizard import ExternalAppEditor
app_editor = ExternalAppEditor(self)
name, xml, ok = app_editor.getDialog()
if name in self._external_app_names:
msg = ('The "%s" external application exists in your GUI.'
' If you want to create a new one, '
'please use other text label' % name)
taurus.warning(msg)
return
if ok:
extapp = ExternalApp.fromXml(xml)
action = extapp.getAction()
action_name = str(action.text())
self.__external_app[action_name] = extapp
self._addExternalAppLauncher(name, action)
def _addExternalAppLauncher(self, name, action):
action_name = str(action.text())
self.__external_app_actions[action_name] = action
self.addExternalAppLauncher(action)
self._external_app_names.append(name)
def removeExternalApp(self, name=None):
'''Remove the given external application from the GUI.
:param name: (str or None) the name of the external application to be
removed
If None given, the user will be prompted
'''
apps = list(self.__external_app.keys()) + self.__permanent_ext_apps
if name is None:
items = sorted(apps)
msg1 = "Remove External application"
msg2 = ("External application to be removed "
"(only custom external applications can be removed).")
name, ok = Qt.QInputDialog.getItem(self, msg1, msg2, items, 0,
False)
if not ok:
return
name = str(name)
if name not in apps:
msg = ('Cannot remove the external application "%s"'
' (not found)' % name)
self.debug(msg)
return
if name in list(self.__external_app.keys()):
self.__external_app.pop(name)
else:
self.__permanent_ext_apps.remove(name)
action = self.__external_app_actions.pop(name)
self._external_app_names.remove(name)
self.deleteExternalAppLauncher(action)
self.debug('External application "%s" removed' % name)
@deprecation_decorator(alt="item factories", rel="4.6.5")
def setCustomWidgetMap(self, map):
'''
Sets the widget map that is used application-wide. This widget map will
be used by default in all TaurusForm Panels belonging to this gui.
:param map: (dict<str,Qt.QWidget>) a dictionary whose keys are device
type strings (e.g. see :class:`PyTango.DeviceInfo`) and
whose values are widgets to be used
.. seealso:: :meth:`TaurusForm.setCustomWidgetMap`, :meth:`getCustomWidgetMap`
'''
self._customWidgetMap = map
@deprecation_decorator(alt="item factories", rel="4.6.5")
def getCustomWidgetMap(self):
'''
Returns the default map used to create custom widgets by the TaurusForms
belonging to this GUI
:return: (dict<str,Qt.QWidget>) a dictionary whose keys are device
type strings (i.e. see :class:`PyTango.DeviceInfo`) and whose
values are widgets to be used
.. seealso:: :meth:`setCustomWidgetMap`
'''
return self._customWidgetMap
def createConfig(self, *args, **kwargs):
'''reimplemented from TaurusMainWindow.createConfig'''
self.updatePermanentCustomPanels(showAlways=False)
self.updatePermanentExternalApplications(showAlways=False)
cfg = TaurusMainWindow.createConfig(self, *args, **kwargs)
return cfg
def removePanel(self, name=None):
''' remove the given panel from the GUI.
.. note:: The panel; is actually removed from the current perspective.
If the panel is saved in other perspectives, it should be removed from
them as well.
:param name: (str or None) the name of the panel to be removed
If None given, the user will be prompted
'''
if name is None:
items = sorted(
[n for n, p in self.__panels.items() if p.isCustom()])
name, ok = Qt.QInputDialog.getItem(self, "Remove Panel",
"Panel to be removed (only custom panels can be removed).\n Important: you may want to save the perspective afterwards,\n and maybe remove the panel from other perspectives as well", items, 0, False)
if not ok:
return
name = str(name)
if name not in self.__panels:
self.debug('Cannot remove panel "%s" (not found)' % name)
return
panel = self.__panels.pop(name)
try:
# in case the widget is a Taurus one and does some cleaning when
# setting model to None
panel.widget().setModel(None)
except:
pass
self.unregisterConfigurableItem(name, raiseOnError=False)
self.removeDockWidget(panel)
panel.setParent(None)
panel.setAttribute(Qt.Qt.WA_DeleteOnClose)
panel.close()
self.debug('Panel "%s" removed' % name)
def createPanel(self, widget, name, floating=False, registerconfig=True, custom=False,
permanent=False, icon=None, instrumentkey=None):
'''
Creates a panel containing the given widget.
:param wiget: (QWidget) the widget to be contained in the panel
:param name: (str) the name of the panel. It will be used in tabs as well as for configuration
:param floating: (bool) whether the panel should be docked or floating. (see note below)
:param registerconfig: (bool) if True, the panel will be registered as a delegate for configuration
:param custom: (bool) if True the panel is to be considered a "custom panel"
:param permanent: (bool) set this to True for panels that need to be recreated when restoring the app
:param icon: (QIcon) icon for the panel
:param instrumentkey: (str) name of an instrument to which this panel is to be associated
:return: (DockWidgetPanel) the created panel
.. note:: On a previous version, there was a mandatory parameter called
`area` (which accepted a Qt.DockWidgetArea or None as values)
this parameter has now been substituted by the keyword
argument `floating`. In order to provide backwards
compatibility, the "floating" keyword argument stays at the
same position as the old `area` argument and if a Qt.DockWidgetArea
value is given, it will be interpreted as floating=True (while if
`None` is passed, it will be interpreted as floating=False.
'''
# backwards compatibility:
if not isinstance(floating, bool):
self.info(
'Deprecation warning: please note that the "area" argument is deprecated. See TaurusGui.createPanel doc')
floating = not(floating)
name = str(name)
if name in self.__panels:
self.info('Panel with name "%s" already exists. Reusing.' % name)
return self.__panels[name]
# create a panel
panel = DockWidgetPanel(None, widget, name, self)
# we will only place panels in this area
self.addDockWidget(Qt.Qt.TopDockWidgetArea, panel)
if len(self.__panels) != 0:
self.tabifyDockWidget(list(self.__panels.values())[-1], panel)
panel.setFloating(floating)
# associate this panel with an instrument
if instrumentkey is not None:
if instrumentkey == self.IMPLICIT_ASSOCIATION:
# see if there is an item whose name is the same as that of the
# panel
for syn in self.__synoptics:
if name in syn.get_item_list():
self.setInstrumentAssociation(name, name)
break
else:
self.setInstrumentAssociation(instrumentkey, name)
if icon is not None:
panel.toggleViewAction().setIcon(icon)
# set flags
panel.setCustom(custom)
panel.setPermanent(permanent)
# register the panel for configuration
if registerconfig:
self.registerConfigDelegate(panel, name=name)
self.__panels[name] = panel
# connect the panel visibility changes
panel.visibilityChanged.connect(self._onPanelVisibilityChanged)
return panel
def getPanel(self, name):
'''get a panel object by name
:return: (DockWidgetPanel)
'''
return self.__panels[str(name)]
def getPanelNames(self):
'''returns the names of existing panels
:return: (list<str>)
'''
return copy.deepcopy(list(self.__panels.keys()))
def _setPermanentExternalApps(self, permExternalApps):
'''creates empty panels for restoring custom panels.
:param permCustomPanels: (list<str>) list of names of custom panels
'''
# first create the panels if they don't actually exist
for name in permExternalApps:
if name not in self._external_app_names:
# create empty action
self.__permanent_ext_apps.append(name)
action = ExternalAppAction('', name)
self._addExternalAppLauncher(name, action)
def _getPermanentExternalApps(self):
return self.__permanent_ext_apps
def _setPermanentCustomPanels(self, permCustomPanels):
'''creates empty panels for restoring custom panels.
:param permCustomPanels: (list<str>) list of names of custom panels
'''
# first create the panels if they don't actually exist
for name in permCustomPanels:
if name not in self.__panels:
self.createPanel(None, name, custom=True, permanent=True)
def _getPermanentCustomPanels(self):
'''
returns a list of panel names for which the custom and permanent flags
are True (i.e., those custom panels that should be stored in
configuration and/or perspectives)
:return: (list<str>)
'''
return [n for n, p in self.__panels.items() if (p.isCustom() and p.isPermanent())]
def updatePermanentCustomPanels(self, showAlways=True):
'''
Shows a dialog for selecting which custom panels should be permanently
stored in the configuration.
:param showAlways: (bool) forces showing the dialog even if there are no new custom Panels
'''
# check if there are some newly created panels that may be made
# permanent
perm = self._getPermanentCustomPanels()
temp = [n for n, p in self.__panels.items() if (
p.isCustom() and not p.isPermanent())]
if len(temp) > 0 or showAlways:
from taurus.qt.qtgui.panel import QDoubleListDlg
dlg = QDoubleListDlg(winTitle='Stored panels',
mainLabel='Select which of the panels should be stored',
label1='Temporary (to be discarded)', label2='Permanent (to be stored)',
list1=temp, list2=perm)
result = dlg.exec_()
if result == Qt.QDialog.Accepted:
# update the permanent Custom Panels
registered = self.getConfigurableItemNames()
for name in dlg.getAll2():
if name not in registered:
self.__panels[name].setPermanent(True)
self.registerConfigDelegate(self.__panels[name], name)
# unregister any panel that is temporary
for name in dlg.getAll1():
self.__panels[name].setPermanent(False)
self.unregisterConfigurableItem(name, raiseOnError=False)
def updatePermanentExternalApplications(self, showAlways=True):
'''
Shows a dialog for selecting which new externals applications
should be permanently stored in the configuration.
:param showAlways: (bool) forces showing the dialog
'''
# check if there are some newly created external applications that may
# be made permanent
#permanet_ext_app = list(self._external_app_names)
if len(self.__external_app) > 0 or showAlways:
from taurus.qt.qtgui.panel import QDoubleListDlg
msg = 'Select which of the external applications should be stored'
dlg = QDoubleListDlg(winTitle='Stored external applications',
mainLabel=msg,
label1='Temporary (to be discarded)',
label2='Permanent (to be stored)',
list1=list(self.__external_app.keys()),
list2=self.__permanent_ext_apps)
result = dlg.exec_()
if result == Qt.QDialog.Accepted:
# update the temporally external applications
for name in dlg.getAll2():
self.__permanent_ext_apps.append(str(name))
if name in self.__external_app:
self.__external_app.pop(str(name))
for name in dlg.getAll1():
self.unregisterConfigurableItem("_extApp[%s]" % str(name),
raiseOnError=False)
def createCustomPanel(self, paneldesc=None):
'''
Creates a panel from a Panel Description and sets it as "custom panel".
:param paneldesc: (PanelDescription) description of the panel to be created
.. seealso:: :meth:`createPanel`
'''
if paneldesc is None:
from taurus.qt.qtgui.taurusgui import PanelDescriptionWizard
paneldesc, ok = PanelDescriptionWizard.getDialog(
self, extraWidgets=self._extraCatalogWidgets)
if not ok:
return
w = paneldesc.getWidget(sdm=Qt.qApp.SDM, setModel=False)
# ----------------------------------------------------------------
# Backwards-compat. Remove when removing CW map support
if self._customWidgetMap and hasattr(w, 'setCustomWidgetMap'):
w.setCustomWidgetMap(self._customWidgetMap)
# ----------------------------------------------------------------
if paneldesc.model is not None:
w.setModel(paneldesc.model)
if isinstance(w, TaurusBaseComponent):
# TODO: allow to select these options in the dialog
w.setModifiableByUser(True)
w.setModelInConfig(True)
self.createPanel(w, paneldesc.name, floating=paneldesc.floating, custom=True,
registerconfig=False, instrumentkey=paneldesc.instrumentkey,
permanent=False)
msg = 'Panel %s created. Drag items to it or use the context menu to customize it' % w.name
self.newShortMessage.emit(msg)
def createMainSynoptic(self, synopticname):
'''
Creates a synoptic panel and registers it as "SelectedInstrument"
reader and writer (allowing selecting instruments from synoptic
'''
try:
jdwFileName = os.path.join(self._confDirectory, synopticname)
from taurus.qt.qtgui.graphic import TaurusJDrawSynopticsView
synoptic = TaurusJDrawSynopticsView()
synoptic.setModel(jdwFileName)
self.__synoptics.append(synoptic)
except Exception as e:
# print repr(e)
msg = 'Error loading synoptic file "%s".\nSynoptic won\'t be available' % jdwFileName
self.error(msg)
self.traceback(level=taurus.Info)
result = Qt.QMessageBox.critical(self, 'Initialization error', '%s\n\n%s' % (
msg, repr(e)), Qt.QMessageBox.Abort | Qt.QMessageBox.Ignore)
if result == Qt.QMessageBox.Abort:
sys.exit()
Qt.qApp.SDM.connectWriter(
"SelectedInstrument", synoptic, "graphicItemSelected")
Qt.qApp.SDM.connectReader(
"SelectedInstrument", synoptic.selectGraphicItem)
# find an unique (and short) name
name = os.path.splitext(os.path.basename(synopticname))[0]
if len(name) > 10:
name = 'Syn'
i = 2
prefix = name
while name in self.__panels:
name = '%s_%i' % (prefix, i)
i += 1
synopticpanel = self.createPanel(synoptic, name, permanent=True,
icon=Qt.QIcon.fromTheme(
'image-x-generic'))
if self.QUICK_ACCESS_TOOLBAR_ENABLED:
toggleSynopticAction = synopticpanel.toggleViewAction()
self.quickAccessToolBar.addAction(toggleSynopticAction)
def createConsole(self, kernels):
msg = ('createConsole() and the "CONSOLE" configuration key are ' +
'deprecated since 4.0.4. Add a panel with a ' +
'silx.gui.console.IPythonWidget widdget instead')
self.deprecated(msg)
try:
from silx.gui.console import IPythonWidget
except ImportError:
self.warning('Cannot import taurus.qt.qtgui.console. ' +
'The Console Panel will not be available')
return
console = IPythonWidget()
self.createPanel(console, "Console", permanent=True,
icon=Qt.QIcon.fromTheme('utilities-terminal'))
def createInstrumentsFromPool(self, macroservername):
'''
Creates a list of instrument panel descriptions by gathering the info
from the Pool. Each panel is a TaurusForm grouping together all those
elements that belong to the same instrument according to the Pool info
:return: (list<PanelDescription>)
'''
instrument_dict = {}
try:
ms = taurus.Device(macroservername)
instruments = ms.getElementsOfType('Instrument')
if instruments is None:
raise Exception()
except Exception as e:
msg = 'Could not fetch Instrument list from "%s"' % macroservername
self.error(msg)
result = Qt.QMessageBox.critical(self, 'Initialization error', '%s\n\n%s' % (
msg, repr(e)), Qt.QMessageBox.Abort | Qt.QMessageBox.Ignore)
if result == Qt.QMessageBox.Abort:
sys.exit()
return []
for i in instruments.values():
i_name = i.full_name
#i_name, i_unknown, i_type, i_pools = i.split()
i_view = PanelDescription(
i_name, classname='TaurusForm', floating=False, model=[])
instrument_dict[i_name] = i_view
from operator import attrgetter
pool_elements = sorted(ms.getElementsWithInterface(
'Moveable').values(), key=attrgetter('name'))
pool_elements += sorted(ms.getElementsWithInterface(
'ExpChannel').values(), key=attrgetter('name'))
pool_elements += sorted(ms.getElementsWithInterface(
'IORegister').values(), key=attrgetter('name'))
for elem in pool_elements:
instrument = elem.instrument
if instrument:
i_name = instrument
# -----------------------------------------------------------
# Support sardana v<2.4 (which used tango names instead of
# taurus full names
e_name = elem.full_name
if not e_name.startswith("tango://"):
e_name = "tango://%s" % e_name
# -----------------------------------------------------------
instrument_dict[i_name].model.append(e_name)
# filter out empty panels
ret = [instrument for instrument in instrument_dict.values()
if len(instrument.model) > 0]
return ret
def __getVarFromXML(self, root, nodename, default=None):
name = root.find(nodename)
if name is None or name.text is None:
return default
else:
return name.text
def _importConfiguration(self, confname):
'''returns the module corresponding to `confname` or to
`tgconf_<confname>`. Note: the `conf` subdirectory of the directory in
which taurusgui.py file is installed is temporally prepended to sys.path
'''
confsubdir = os.path.join(os.path.abspath(os.path.dirname(
__file__)), 'conf') # the path to a conf subdirectory of the place where taurusgui.py is
oldpath = sys.path
try:
# add the conf subdirectory dir to the pythonpath
sys.path = [confsubdir] + sys.path
conf = __import__(confname)
except ImportError:
altconfname = "tgconf_%s" % confname
try: