Skip to content

sanp_app

Classes¤

SanPyApp ¤

Bases: QApplication

Source code in sanpy/interface/sanpy_app.py
 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
class SanPyApp(QtWidgets.QApplication):
    def __init__(self, argv):
        super().__init__(argv)

        self._windowList = []

        firstTimeRunning = sanpy._util.addUserPath()
        if firstTimeRunning:
            logger.info("  We created <user>/Documents/Sanpy and need to restart")

        self._fileLoaderDict = sanpy.fileloaders.getFileLoaders(verbose=True)

        self._detectionClass : sanpy.bDetection = sanpy.bDetection()

        self._configDict : sanpy.interface.preferences = sanpy.interface.preferences(self)
        self._currentWindowGeometry = {
            'x': self._configDict['windowGeometry']['x'],
            'y': self._configDict['windowGeometry']['y'],
            'width': self._configDict['windowGeometry']['width'],
            'height': self._configDict['windowGeometry']['height']
        }

        self._plugins = sanpy.interface.bPlugins(sanpyApp=self)
        self._analysisUtil = sanpy.bAnalysisUtil()

        # self._useDarkStyle = self._configDict["useDarkStyle"]
        self.toggleStyleSheet(buildingInterface=True)

        appIconPath = getAppIconPath()    
        if os.path.isfile(appIconPath):
            # logger.info(f'  app.setWindowIcon with: "{appIconPath}"')
            self.setWindowIcon(QtGui.QIcon(appIconPath))
        else:
            logger.warning(f"Did not find appIconPath: {appIconPath}")

        logger.info('-->> SanPyApp done initializing')

    @property
    def useDarkStyle(self):
        # return self._useDarkStyle
        return self._configDict["useDarkStyle"]

    def toggleStyleSheet(self, doDark=None, buildingInterface=False):
        logger.info("")
        if doDark is None:
            # doDark = not self._useDarkStyle
            doDark = self.useDarkStyle
        # self._useDarkStyle = doDark
        if doDark:
            # v1
            # self.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt5'))
            # v2
            qdarktheme.setup_theme("dark")

            pg.setConfigOption("background", "k")
            pg.setConfigOption("foreground", "w")
        else:
            # v1
            # self.setStyleSheet('')
            # v2
            qdarktheme.setup_theme("light")

            pg.setConfigOption("background", "w")
            pg.setConfigOption("foreground", "k")

        self.configDict["useDarkStyle"] = doDark  # self._useDarkStyle

        if not buildingInterface:
            # self.myScatterPlotWidget.defaultPlotLayout()
            # self.myScatterPlotWidget.buildUI(doRebuild=True)

            # 20231229 removed
            # self.myDetectionWidget.mySetTheme()
            pass

        if buildingInterface:
            pass
        else:
            pass
            # msg = QtWidgets.QMessageBox()
            # msg.setIcon(QtWidgets.QMessageBox.Warning)
            # msg.setText("Theme Changed")
            # msg.setInformativeText('Please restart SanPy for changes to take effect.')
            # msg.setWindowTitle("Theme Changed")
            # retval = msg.exec_()

            # self.configDict.save()

    def getAnalysisUtil(self):
        return self._analysisUtil

    def getPlugins(self):
        return self._plugins

    def getFileLoaderDict(self):
        return self._fileLoaderDict

    def getDetectionClass(self) -> "sanpy.bDetection":
        return self._detectionClass

    # todo: the next three functions can be reduced to just one!

    @property
    def configDict(self):
        return self._configDict

    def getConfigDict(self) -> "sanpy.interface.preferences":
        return self._configDict

    def getOptions(self):
        return self._configDict

    def newWindowGeometry(self) -> dict:
        """Get geometry for a new window.
        """
        xyOffset = 20
        newWindowGeometry = {
            'x': self._currentWindowGeometry['x'] + xyOffset,
            'y': self._currentWindowGeometry['y'] + xyOffset,
            'width': self._currentWindowGeometry['width'],
            'height': self._currentWindowGeometry['height']
        }

        self._currentWindowGeometry = newWindowGeometry

        return newWindowGeometry

    def openSanPyWindow(self, path=None, sweep=None, spikeNumber=None):
        """Open a new SanPyWindow from a path.

        Can be either a file or a folder.

        Parameters
        ----------
        sweep : int
            Only works for file path
        """

        logger.info(f'path:{path}')
        logger.info(f'   sweep:{sweep}')
        logger.info(f'   spikeNumber:{spikeNumber}')

        # check if it is open
        foundWindow = None
        for aWindow in self._windowList:
            if aWindow.path == path:
                logger.info('   raising existing window')
                aWindow.raise_()  # bring to front, raise is a python keyword
                aWindow.activateWindow()  # bring to front
                foundWindow = aWindow

        # open new window
        if foundWindow is None:
            logger.info('   opening new window')
            foundWindow = SanPyWindow(self, path)
            foundWindow.show()
            foundWindow.raise_()  # bring to front, raise is a python keyword
            foundWindow.activateWindow()  # bring to front
            self._windowList.append(foundWindow)

        # only set sweep and select spike if
        # we opened a file path
        if path is not None:
            if os.path.isfile(path):
                if sweep is not None:
                    # _ba = foundWindow.get_bAnalysis()
                    # foundWindow.slot_selectSweep(_ba, sweep)
                    foundWindow.selectSweep_external(sweep)

                if spikeNumber is not None:
                    # foundWindow.slot_selectSpike(sDict)
                    foundWindow.selectSpike(spikeNumber, doZoom=False)

        # add to recent opened windows
        if path is not None:
            self.getOptions().addPath(path)

        return foundWindow

    def closeSanPyWindow(self, theWindow : SanPyWindow):
        """Remove theWindow from self._windowList.
        """
        logger.info('todo: implement this')
        logger.info('  remove sanpy window from app list of windows')
        for idx, aWindow in enumerate(self._windowList):
            if aWindow == theWindow:
                _removedValue = self._windowList.pop(idx)

    def _onHelpMenuAction(self, name: str):
        if name == "SanPy Help (Opens In Browser)":
            url = "https://cudmore.github.io/SanPy/desktop-application"
            webbrowser.open(url, new=2)

    def _onPreferencesMenuAction(self):
        logger.info('')

    def _onAboutMenuAction(self):
        """Show a dialog with help.
        """
        print(self._getVersionInfo())
        self.getSanPyApp()._onAboutMenuAction
        return

        dlg = QtWidgets.QDialog(self)
        dlg.setWindowTitle('About SanPy')

        vLayout = QtWidgets.QVBoxLayout()

        _versionInfo = self._getVersionInfo()
        for k,v in _versionInfo.items():
            aText = k + ' ' + str(v)
            aLabel = QtWidgets.QLabel(aText)

            if 'https' in v:
                aLabel.setText(f'{k} <a href="{v}">{v}</a>')
                aLabel.setTextFormat(QtCore.Qt.RichText)
                aLabel.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction)
                aLabel.setOpenExternalLinks(True)

            if k == 'email':
                # <a href = "mailto: abc@example.com">Send Email</a>
                aLabel.setText(f'{k} <a href="mailto:{v}">{v}</a>')
                aLabel.setTextFormat(QtCore.Qt.RichText)
                aLabel.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction)
                aLabel.setOpenExternalLinks(True)

            vLayout.addWidget(aLabel)

        dlg.setLayout(vLayout)

        dlg.exec()

    def _getVersionInfo(self) -> dict:
        retDict = {}

        #import platform
        _platform = platform.machine()
        # arm64
        # x86_64

        # from sanpy.version import __version__

        # retDict['SanPy version'] = __version__
        retDict['SanPy version'] = sanpy.__version__
        retDict['Python version'] = platform.python_version()
        retDict['Python platform'] = _platform  # platform.platform()
        retDict['PyQt version'] = QtCore.__version__  # when using import qtpy
        # retDict['Bundle folder'] = sanpy._util.getBundledDir()
        # retDict['Log file'] = sanpy.sanpyLogger.getLoggerFile()
        retDict['GitHub'] = 'https://github.com/cudmore/sanpy'
        retDict['Documentation'] = 'https://cudmore.github.io/SanPy/'
        retDict['email'] = 'rhcudmore@ucdavis.edu'

        return retDict

Functions¤

closeSanPyWindow(theWindow) ¤

Remove theWindow from self._windowList.

Source code in sanpy/interface/sanpy_app.py
240
241
242
243
244
245
246
247
def closeSanPyWindow(self, theWindow : SanPyWindow):
    """Remove theWindow from self._windowList.
    """
    logger.info('todo: implement this')
    logger.info('  remove sanpy window from app list of windows')
    for idx, aWindow in enumerate(self._windowList):
        if aWindow == theWindow:
            _removedValue = self._windowList.pop(idx)
newWindowGeometry() ¤

Get geometry for a new window.

Source code in sanpy/interface/sanpy_app.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def newWindowGeometry(self) -> dict:
    """Get geometry for a new window.
    """
    xyOffset = 20
    newWindowGeometry = {
        'x': self._currentWindowGeometry['x'] + xyOffset,
        'y': self._currentWindowGeometry['y'] + xyOffset,
        'width': self._currentWindowGeometry['width'],
        'height': self._currentWindowGeometry['height']
    }

    self._currentWindowGeometry = newWindowGeometry

    return newWindowGeometry
openSanPyWindow(path=None, sweep=None, spikeNumber=None) ¤

Open a new SanPyWindow from a path.

Can be either a file or a folder.

Parameters:

Name Type Description Default
sweep int

Only works for file path

None
Source code in sanpy/interface/sanpy_app.py
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
def openSanPyWindow(self, path=None, sweep=None, spikeNumber=None):
    """Open a new SanPyWindow from a path.

    Can be either a file or a folder.

    Parameters
    ----------
    sweep : int
        Only works for file path
    """

    logger.info(f'path:{path}')
    logger.info(f'   sweep:{sweep}')
    logger.info(f'   spikeNumber:{spikeNumber}')

    # check if it is open
    foundWindow = None
    for aWindow in self._windowList:
        if aWindow.path == path:
            logger.info('   raising existing window')
            aWindow.raise_()  # bring to front, raise is a python keyword
            aWindow.activateWindow()  # bring to front
            foundWindow = aWindow

    # open new window
    if foundWindow is None:
        logger.info('   opening new window')
        foundWindow = SanPyWindow(self, path)
        foundWindow.show()
        foundWindow.raise_()  # bring to front, raise is a python keyword
        foundWindow.activateWindow()  # bring to front
        self._windowList.append(foundWindow)

    # only set sweep and select spike if
    # we opened a file path
    if path is not None:
        if os.path.isfile(path):
            if sweep is not None:
                # _ba = foundWindow.get_bAnalysis()
                # foundWindow.slot_selectSweep(_ba, sweep)
                foundWindow.selectSweep_external(sweep)

            if spikeNumber is not None:
                # foundWindow.slot_selectSpike(sDict)
                foundWindow.selectSpike(spikeNumber, doZoom=False)

    # add to recent opened windows
    if path is not None:
        self.getOptions().addPath(path)

    return foundWindow

Functions¤

main() ¤

Main entry point for the SanPy desktop app.

Configured in setup.py

Source code in sanpy/interface/sanpy_app.py
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
def main():
    """Main entry point for the SanPy desktop app.

    Configured in setup.py
    """
    # logger.info('calling freeze support')
    # freeze_support()

    logger.info(f"Starting sanpy_app.py in main()")
    # date_time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # logger.info(f'    {date_time_str}')

    # _version = _getVersionInfo()
    # for k,v in _version.items():
    #     logger.info(f'{k} {v}')

    # app = QtWidgets.QApplication(sys.argv)
    app = SanPyApp(sys.argv)

    app.setQuitOnLastWindowClosed(False)

    # for manuscript we need to allow user to set light/dark theme
    # was this
    # v1
    # app.setStyleSheet(qdarkstyle.load_stylesheet(qt_api=os.environ['PYQTGRAPH_QT_LIB']))
    # v2
    qdarktheme.setup_theme()

    # w = SanPyWindow()
    # w.show()
    # w.raise_()  # bring to front, raise is a python keyword
    # w.activateWindow()  # bring to front
    app.openSanPyWindow()

    sys.exit(app.exec_())
All material is Copyright 2011-2023 Robert H. Cudmore