gui_helper.py 5.86 KB
Newer Older
1
2
3
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
4
5
#   NScD Oak Ridge National Laboratory, European Spallation Source,
#   Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6
7
# SPDX - License - Identifier: GPL - 3.0 +
from qtpy.QtWidgets import (QApplication)  # noqa
8
from qtpy import QtCore, QtGui
9
import matplotlib
Savici, Andrei T's avatar
Savici, Andrei T committed
10
11
import sys
import os
12
13
14
15
16
17
18
19
try:
    from mantid import __version__ as __mtd_version
    from mantid import _bindir as __mtd_bin_dir
    # convert to major.minor
    __mtd_version = '.'.join(__mtd_version.split(".")[:2])
except ImportError:  # mantid not found
    __mtd_version = ''
    __mtd_bin_dir=''
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35


def set_matplotlib_backend():
    '''MUST be called before anything tries to use matplotlib

    This will set the backend if it hasn't been already. It also returns
    the name of the backend to be the name to be used for importing the
    correct matplotlib widgets.'''
    backend = matplotlib.get_backend()
    if backend.startswith('module://'):
        if backend.endswith('qt4agg'):
            backend = 'Qt4Agg'
        elif backend.endswith('workbench') or backend.endswith('qt5agg'):
            backend = 'Qt5Agg'
    else:
        from qtpy import PYQT4, PYQT5  # noqa
Peterson, Peter's avatar
Peterson, Peter committed
36
        if PYQT5:
37
            backend = 'Qt5Agg'
Peterson, Peter's avatar
Peterson, Peter committed
38
39
        elif PYQT4:
            backend = 'Qt4Agg'
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
        else:
            raise RuntimeError('Do not know which matplotlib backend to set')
        matplotlib.use(backend)
    return backend


def get_qapplication():
    ''' Example usage:

    app, within_mantid = get_qapplication()
    reducer = eventFilterGUI.MainWindow()  # the main ui class in this file
    reducer.show()
    if not within_mantid:
        sys.exit(app.exec_())'''
    app = QApplication.instance()
    if app:
        return app, app.applicationName().lower().startswith('mantid')
    else:
        return QApplication(sys.argv), False
59

Savici, Andrei T's avatar
Savici, Andrei T committed
60

Peterson, Peter's avatar
Peterson, Peter committed
61
def __to_external_url(interface_name: str, section: str, external_url: str) -> QtCore.QUrl:
62
    if not external_url:
Peterson, Peter's avatar
Peterson, Peter committed
63
64
        template = 'http://docs.mantidproject.org/nightly/interfaces/{}/{}.html'
        external_url = template.format(section, interface_name)
65
66
67
68

    return QtCore.QUrl(external_url)


Peterson, Peter's avatar
Peterson, Peter committed
69
def __to_qthelp_url(interface_name: str, section: str, qt_url: str) -> str:
70
71
72
    if qt_url:
        return qt_url
    else:
Peterson, Peter's avatar
Peterson, Peter committed
73
74
        template = 'qthelp://org.sphinx.mantidproject.{}/doc/interfaces/{}/{}.html'
        return template.format(__mtd_version, section, interface_name)
75
76
77
78
79
80
81
82
83
84
85
86


def __get_collection_file(collection_file: str) -> str:
    if not collection_file:
        if not __mtd_bin_dir:
            return 'HELP COLLECTION FILE NOT FOUND'
        else:
            collection_file = os.path.join(__mtd_bin_dir, '../docs/qthelp/MantidProject.qhc')

    return os.path.abspath(collection_file)


87
def show_interface_help(mantidplot_name, assistant_process, area: str='',
88
89
                        collection_file: str='',
                        qt_url: str='', external_url: str=""):
90
91
92
    ''' Shows the help page for a custom interface
    @param mantidplot_name: used by showCustomInterfaceHelp
    @param assistant_process: needs to be started/closed from outside (see example below)
93
94
95
96
97
98
    @param collection_file: qth file containing the help in format used by qtassistant. The default is
    ``mantid._bindir + '../docs/qthelp/MantidProject.qhc'``
    @param qt_url: location of the help in the qth file. The default value is
    ``qthelp://org.sphinx.mantidproject.{mtdversion}/doc/interfaces/{mantidplot_name}.html``.
    @param external_url: location of external page to be displayed in the default browser. The default value is
    ``http://docs.mantidproject.org/nightly/interfaces/framework/{mantidplot_name}.html``
99

100
    Example using defaults:
101
102
103
104
105
106
107
108

    #in the __init__ function of the GUI add:
    self.assistant_process = QtCore.QProcess(self)
    self.mantidplot_name='DGS Planner'

    #add a help function in the GUI
    def help(self):
       show_interface_help(self.mantidplot_name,
109
                           self.assistant_process)
110
111
112
113
114
115
116
117

    #make sure you close the qtassistant when the GUI is closed
    def closeEvent(self, event):
        self.assistant_process.close()
        self.assistant_process.waitForFinished()
        event.accept()
    '''
    try:
118
        # try using built-in help in mantid
119
        import mantidqt
120
        mantidqt.interfacemanager.InterfaceManager().showCustomInterfaceHelp(mantidplot_name, area)
121
    except: #(ImportError, ModuleNotFoundError) raises the wrong type of error
122
123
124
        # built-in help failed, try external qtassistant then give up and launch a browser

        # cleanup previous version
125
126
        assistant_process.close()
        assistant_process.waitForFinished()
127
128

        # where to expect qtassistant
129
130
        helpapp = QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.BinariesPath) + QtCore.QDir.separator()
        helpapp += 'assistant'
131
132

        collection_file = __get_collection_file(collection_file)
133
        if os.path.isfile(helpapp) and os.path.isfile(collection_file):
134
135
136
            # try to find the collection file and launch qtassistant
            args = ['-enableRemoteControl',
                    '-collectionFile', collection_file,
Peterson, Peter's avatar
Peterson, Peter committed
137
                    '-showUrl', __to_qthelp_url(mantidplot_name, section, qt_url)]
138

139
140
141
142
            assistant_process.close()
            assistant_process.waitForFinished()
            assistant_process.start(helpapp, args)
        else:
143
            # give up and upen a URL in default browser
144
145
146
147
148
            openUrl=QtGui.QDesktopServices.openUrl
            sysenv=QtCore.QProcessEnvironment.systemEnvironment()
            ldp=sysenv.value('LD_PRELOAD')
            if ldp:
                del os.environ['LD_PRELOAD']
149
150

            # create a url to the help in the default location
Peterson, Peter's avatar
Peterson, Peter committed
151
            openUrl(__to_external_url(mantidplot_name, section, external_url))
152

153
154
            if ldp:
                os.environ['LD_PRELOAD']=ldp