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 | class SanPyApp(QtWidgets.QApplication):
"""Own the SanPy desktop application and its shared services."""
def __init__(
self, argv: list[str], sanpy_paths: SanPyPaths | None = None
) -> None:
"""Initialize the desktop application.
Args:
argv: Command-line arguments passed to Qt.
sanpy_paths: Optional path manager, primarily for test isolation.
"""
# Qt WebEngine plugins require shared contexts before QApplication exists.
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)
super().__init__(argv)
self.sanpy_paths = sanpy_paths or SanPyPaths()
self._windowList: list[SanPyWindow] = []
# Keep analysis windows alive until Qt emits their destroyed signal.
self._quitInProgress = False
self._analysisLoaderThread: _AnalysisDirLoaderThread | None = None
first_time_running = self.sanpy_paths.ensure_user_files()
if first_time_running:
logger.info(" We created <user>/Documents/Sanpy and need to restart")
self._fileLoaderDict = getFileLoaders(verbose=True)
self._detectionClass : sanpy.bDetection = sanpy.bDetection(self.sanpy_paths)
self._configDict: preferences = preferences(
self, first_time_running=first_time_running
)
self._currentWindowGeometry = {
'x': self._configDict['windowGeometry']['x'],
'y': self._configDict['windowGeometry']['y'],
'width': self._configDict['windowGeometry']['width'],
'height': self._configDict['windowGeometry']['height']
}
# Import after sanpy.interface finishes initializing its plugin helpers.
from sanpy.interface.bPlugins import bPlugins
self._plugins = bPlugins(sanpyApp=self)
# self._useDarkStyle = self._configDict["useDarkStyle"]
self.toggleStyleSheet(buildingInterface=True)
appIconPath = getAppIconPath(self.sanpy_paths)
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}")
self.openRecentMenu = None
# open the widget to allow open from recent
self._openFirstWidget = None
self.openFirstWidget()
logger.info('-->> SanPyApp done initializing')
def openFirstWidget(self):
"""Open a window to allow opening of new and recent files and folder.
"""
self._openFirstWidget = openFirstWidget(self)
logger.info(' raising openFirstWidget')
self._openFirstWidget.show()
# self._openFirstWidget.raise_() # bring to front, raise is a python keyword
# self._openFirstWidget.activateWindow() # bring to front
def showOpenFirstWidget(self):
"""Show and activate the reusable file/folder launcher."""
self._openFirstWidget.show()
self._openFirstWidget.raise_()
self._openFirstWidget.activateWindow()
def hasAnalysisWindows(self) -> bool:
"""Return True when at least one analysis window is registered."""
return bool(self._windowList)
def isLastAnalysisWindow(self, window: SanPyWindow) -> bool:
"""Return True when ``window`` is the only registered analysis window."""
return len(self._windowList) == 1 and self._windowList[0] is window
def _register_sanpy_window(self, window: SanPyWindow) -> None:
"""Register an analysis window until Qt destroys it.
Args:
window: Analysis window whose Qt lifetime should be tracked.
"""
window_id = id(window)
# Capture only the immutable ID. Capturing the window in this callback
# would create another strong Python reference to the closing widget.
window.destroyed.connect(
partial(self._on_sanpy_window_destroyed, window_id)
)
self._windowList.append(window)
def _on_sanpy_window_destroyed(
self,
window_id: int,
_destroyed_object: QtCore.QObject | None = None,
) -> None:
"""Remove a window from the registry after Qt destroys it.
Args:
window_id: Python identity recorded when the window was registered.
_destroyed_object: QObject supplied by Qt's ``destroyed`` signal.
"""
# Do not inspect the emitted QObject because its C++ destruction is
# already in progress. The stable Python ID is sufficient for removal.
for index, window in enumerate(self._windowList):
if id(window) == window_id:
self._windowList.pop(index)
return
@property
def quitInProgress(self) -> bool:
return self._quitInProgress
def requestQuit(self) -> bool:
"""Ask every analysis window to approve, then quit the application.
Saves are intentionally performed as each window is reviewed. If a later
window cancels, earlier successful saves remain saved, but no windows
have been closed.
"""
if self._quitInProgress:
return False
if self.isAnalysisLoading():
self._openFirstWidget.slot_updateStatus(
"Please wait for the current recording load to finish."
)
return False
windows = list(self._windowList)
for window in windows:
if not window.prepareToClose():
return False
self._quitInProgress = True
for window in windows:
window.close()
if self._openFirstWidget is not None:
self._openFirstWidget.close()
self.quit()
return True
def _buildMenus(
self,
mainMenu: QtWidgets.QMenuBar,
saveFolderAnalysisAction: QtWidgets.QAction | None = None,
) -> QtWidgets.QAction | None:
"""Build the shared application menus for a SanPy window.
Args:
mainMenu: Menu bar that receives the shared menus.
saveFolderAnalysisAction: Optional window-specific folder-save
action. The launcher does not supply one.
Returns:
Help-menu action used to insert window-specific menus before Help.
"""
# fileMenu = mainMenu.addMenu("&File")
fileMenu = mainMenu.addMenu("File")
loadFileAction = QtWidgets.QAction("Open File...", self)
loadFileAction.setCheckable(False) # setChecked is True by default?
loadFileAction.setShortcut("Ctrl+O")
loadFileAction.triggered.connect(self.loadFile)
fileMenu.addAction(loadFileAction)
loadFolderAction = QtWidgets.QAction("Open Folder...", self)
loadFolderAction.setCheckable(False) # setChecked is True by default?
loadFolderAction.triggered.connect(self.loadFolder)
fileMenu.addAction(loadFolderAction)
# open recent (submenu) will show two lists, one for files and then one for folders
self.openRecentMenu = QtWidgets.QMenu("Open Recent ...")
self.openRecentMenu.aboutToShow.connect(self._refreshOpenRecent)
fileMenu.addMenu(self.openRecentMenu)
if saveFolderAnalysisAction is not None:
fileMenu.addSeparator()
fileMenu.addAction(saveFolderAnalysisAction)
fileMenu.addSeparator()
# QKeySequence.Close maps to Command-W on macOS and Ctrl-W on Windows.
# Parent the action to this menu's window so only the active window closes.
window = mainMenu.window()
closeWindowAction = QtWidgets.QAction("Close Window", window)
closeWindowAction.setShortcut(QtGui.QKeySequence.Close)
closeWindowAction.setShortcutContext(QtCore.Qt.WindowShortcut)
closeWindowAction.triggered.connect(self._close_active_menu_window)
fileMenu.addAction(closeWindowAction)
fileMenu.addSeparator()
savePreferencesAction = QtWidgets.QAction("Save Preferences", self)
savePreferencesAction.triggered.connect(self.configDict.save)
fileMenu.addAction(savePreferencesAction)
quitAction = QtWidgets.QAction("Quit", self)
quitAction.setMenuRole(QtWidgets.QAction.QuitRole)
quitAction.setShortcut(QtGui.QKeySequence.Quit)
quitAction.triggered.connect(self.requestQuit)
fileMenu.addAction(quitAction)
# moved to SanPyWindow, see self.getWindowsMenu()
# show open SanPyWindow(s)
# self.windowsMenu = mainMenu.addMenu('&Window')
# self.windowsMenu = mainMenu.addMenu('Window')
# self.windowsMenu.aboutToShow.connect(self._refreshWindowsMenu)
# self._refreshWindowsMenu()
# help menu
# self.helpMenu = mainMenu.addMenu("&Help")
self.helpMenu = mainMenu.addMenu("Help")
name = "SanPy Help (Opens In Browser)"
action = QtWidgets.QAction(name, self)
action.triggered.connect(partial(self._onHelpMenuAction, name))
self.helpMenu.addAction(action)
# this actually does not show up in the help menu!
# On macOS PyQt reroutes it to the main python/SanPy menu
name = "About SanPy"
action = QtWidgets.QAction(name, self)
action.triggered.connect(self._onAboutMenuAction)
self.helpMenu.addAction(action)
# like the help menu, this gets rerouted to the main python/sanp menu
name = "Preferences ..."
action = QtWidgets.QAction(name, self)
action.triggered.connect(self._onPreferencesMenuAction)
self.helpMenu.addAction(action)
# get help menu as action so other windows can insert their menus before it
# e.g. SanPyWindow inserts (View, Windows) menus
# logger.info('mainMenu is now')
self._helpMenuAction = None
for _action in mainMenu.actions():
actionText = _action.text()
# print(' ', _action.menu(), actionText, _action)
if actionText == 'Help':
self._helpMenuAction = _action
return self._helpMenuAction
def _close_active_menu_window(self, _checked: bool = False) -> None:
"""Close the active owner window or one of its registered plugins.
Args:
_checked: Unused checked state emitted by ``QAction.triggered``.
"""
action = self.sender()
if not isinstance(action, QtWidgets.QAction):
logger.error("Close Window was triggered without an owning action.")
return
window = action.parent()
if not isinstance(window, QtWidgets.QWidget):
logger.error("Close Window action does not have a window parent.")
return
active_window = QtWidgets.QApplication.activeWindow()
if active_window is window:
window.close()
return
# Native menu shortcuts can be consumed before a plugin receives its
# key event. Route the command only to a plugin owned by this window.
for plugin in getattr(window, "_openPluginSet", set()):
plugin_window = plugin.getWidget() if hasattr(plugin, "getWidget") else plugin
if active_window is plugin_window:
plugin_window.close()
return
# def _refreshWindowsMenu(self):
def getWindowsMenu(self, aWindowsMenu):
# aWindowsMenu = QtWidgets.QMenu('&Window')
# open first widget
action = QtWidgets.QAction('Open Files and Folders', self, checkable=True)
if self._openFirstWidget is not None:
action.setChecked(self._openFirstWidget.isActiveWindow())
action.triggered.connect(partial(self._openFirstWidgetAction))
aWindowsMenu.addAction(action)
aWindowsMenu.addSeparator()
for _sanPyWindow in self._windowList:
path = _sanPyWindow.path
action = QtWidgets.QAction(path, self, checkable=True)
action.setChecked(_sanPyWindow.isActiveWindow())
action.triggered.connect(partial(self._windowsMenuAction, _sanPyWindow, path))
# self.windowsMenu.addAction(action)
aWindowsMenu.addAction(action)
return aWindowsMenu
# was a open plugin menu
# move back into SanPyWindow and append open widgets
# for _widget in QtWidgets.QApplication.topLevelWidgets():
# if 'sanpy.interface.plugins' in str(type(_widget)):
# myHumanName = _widget.myHumanName
# print(f'{myHumanName} {_widget}')
# action = QtWidgets.QAction(myHumanName, self, checkable=True)
# action.setChecked(_widget.isActiveWindow())
# action.triggered.connect(partial(self._windowsMenuAction, _widget, myHumanName))
# self.windowsMenu.addAction(action)
def get_open_first_widget(self) -> "openFirstWidget":
"""Get the open first widget.
"""
return self._openFirstWidget
def _openFirstWidgetAction(self):
self._openFirstWidget.show()
self._openFirstWidget.raise_()
self._openFirstWidget.activateWindow() # bring to front
def _refreshOpenRecent(self) -> None:
"""Rebuild the recent file/folder menu from preferences."""
self.openRecentMenu.clear()
# add files
for recentFile in self.configDict.getRecentFiles():
loadFileAction = QtWidgets.QAction(recentFile, self)
loadFileAction.triggered.connect(
partial(self.startOpenSanPyWindow, recentFile)
)
self.openRecentMenu.addAction(loadFileAction)
self.openRecentMenu.addSeparator()
# add folders
for recentFolder in self.configDict.getRecentFolder():
loadFolderAction = QtWidgets.QAction(recentFolder, self)
loadFolderAction.triggered.connect(
partial(self.startOpenSanPyWindow, recentFolder)
)
self.openRecentMenu.addAction(loadFolderAction)
self.openRecentMenu.addSeparator()
clear_action = self.openRecentMenu.addAction("Clear Recents")
clear_action.triggered.connect(self._clearRecent)
def _clearRecent(self, _checked: bool = False) -> None:
"""Clear recent paths and refresh the reusable launcher.
Args:
_checked: Unused checked state emitted by ``QAction.triggered``.
"""
self.configDict.clearRecent()
if self._openFirstWidget is not None:
self._openFirstWidget.refreshRecent()
def _windowsMenuAction(self, aSanPyWindow : "SanPyWindow", path, isChecked):
"""
Parameters
----------
widget : QtWidgets.QWidget
Either self or an open plugin widget
path : str
Name of the window
"""
# don't toggle visibility
# widget.setVisible(not widget.isVisible())
logger.info(f'{aSanPyWindow} {path} {isChecked}')
self.setActiveWindow(aSanPyWindow)
aSanPyWindow.activateWindow()
aSanPyWindow.raise_()
def _recording_file_filter(self) -> str:
"""Build the file-dialog filter from registered recording loaders.
Returns:
Qt file filter containing every supported recording extension.
"""
extensions = sorted(
extension if extension.startswith(".") else f".{extension}"
for extension in self._fileLoaderDict
)
patterns = " ".join(f"*{extension}" for extension in extensions)
return f"SanPy recordings ({patterns})"
def _is_supported_recording(self, file_path: str | os.PathLike[str]) -> bool:
"""Return whether a file has a registered recording loader.
Args:
file_path: Recording path to validate.
Returns:
True when the file extension has a registered loader.
"""
supported_extensions = {
extension.lower()
if extension.startswith(".")
else f".{extension.lower()}"
for extension in self._fileLoaderDict
}
return pathlib.Path(file_path).suffix.lower() in supported_extensions
def loadFile(
self,
filePath: str | os.PathLike[str] | bool | None = None,
) -> None:
"""Prompt for one recording, then open it in an analysis window.
Args:
filePath: Explicit recording path. Qt may pass a boolean when this
method is connected directly to a menu action.
"""
logger.info(f'filePath:"{filePath}" {type(filePath)}')
# ask user for file
if filePath is None or isinstance(filePath, bool):
filePath, _filter = QtWidgets.QFileDialog.getOpenFileName(
caption="Select a raw data file",
filter=self._recording_file_filter(),
)
if len(filePath) == 0:
return
# filePath is a tuple like
# ('/Users/cudmore/Sites/SanPy/data/19114000.abf', 'All Files (*)')
# filePath = filePath[0]
elif os.path.isfile(filePath):
pass
else:
logger.warning(f' Did not load file path "{filePath}"')
return
logger.info(f' user selected open file {filePath}')
# spawn a new window
logger.info(' spawning new window')
self.startOpenSanPyWindow(filePath)
def loadFolder(self, path : str = None, folderDepth=None):
"""Load a folder of raw data files.
Parameters
----------
path : str
folderDepth : int or None
"""
if folderDepth is None:
# get the depth from file list widget
#folderDepth = self._fileListWidget.getDepth()
folderDepth = 1
logger.info(f"Loading depth:{folderDepth} path: {path}")
# ask user for folder
if path is None:
path = str(
QtWidgets.QFileDialog.getExistingDirectory(
caption="Select folder with raw data files"
)
)
if len(path) == 0:
return
if not os.path.isdir(path):
logger.warning(f' Did not load path "{path}"')
return
self.startOpenSanPyWindow(path)
def getAppIconPath(self) -> str:
"""Return the application icon path.
Returns:
Application icon path for source or frozen execution.
"""
return getAppIconPath(self.sanpy_paths)
@property
def useDarkStyle(self):
# return self._useDarkStyle
return self._configDict["useDarkStyle"]
def toggleStyleSheet(
self, doDark: bool | None = None, buildingInterface: bool = False
) -> None:
"""Apply the selected Qt and pyqtgraph application theme.
Args:
doDark: Whether to use the dark theme. The saved preference is used
when omitted.
buildingInterface: Whether the application is still constructing
its initial interface.
"""
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:
# pyqtgraph configuration options are defaults for new widgets;
# refresh plots that already belong to every open analysis window.
for window in tuple(self._windowList):
window.myDetectionWidget.setPlotTheme(doDark)
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 isAnalysisLoading(self) -> bool:
"""Return whether an interactive analysis-directory load is active."""
return self._analysisLoaderThread is not None
def startOpenSanPyWindow(
self,
path: str | os.PathLike[str],
_checked: bool = False,
*,
sweep: int | None = None,
spikeNumber: int | None = None,
) -> None:
"""Start an interactive analysis-window load in a worker thread.
Args:
path: Recording or folder to load.
_checked: Unused checked state emitted by a Qt action.
sweep: Optional sweep to select after loading a recording.
spikeNumber: Optional spike to select after loading a recording.
"""
del _checked
path_string = os.fspath(path)
# Existing and unsupported paths complete synchronously without loading.
if any(window.path == path_string for window in self._windowList):
self.openSanPyWindow(path_string, sweep, spikeNumber)
return
if os.path.isfile(path_string) and not self._is_supported_recording(
path_string
):
self.openSanPyWindow(path_string, sweep, spikeNumber)
return
if not os.path.isfile(path_string) and not os.path.isdir(path_string):
message = f'Cannot open missing path "{path_string}".'
logger.warning(message)
self._openFirstWidget.slot_updateStatus(message)
return
if self.isAnalysisLoading():
self._openFirstWidget.slot_updateStatus(
"Please wait for the current recording load to finish."
)
return
if os.path.isfile(path_string):
folder_depth = 1
else:
folder_depth = self.configDict["fileList"]["Folder Depth"]
self.showOpenFirstWidget()
self._openFirstWidget.slot_updateStatus(
f'Loading "{path_string}" ...'
)
loader = _AnalysisDirLoaderThread(
path_string,
folder_depth,
self.getFileLoaderDict(),
parent=self,
)
self._analysisLoaderThread = loader
loader.statusUpdated.connect(self._openFirstWidget.slot_updateStatus)
loader.loaded.connect(
partial(
self._onAnalysisDirLoaded,
path_string,
sweep,
spikeNumber,
)
)
loader.failed.connect(
partial(self._onAnalysisDirLoadFailed, path_string)
)
loader.finished.connect(self._onAnalysisLoaderFinished)
loader.start()
def _onAnalysisDirLoaded(
self,
path: str,
sweep: int | None,
spike_number: int | None,
analysis_dir: sanpy.analysisDir,
) -> None:
"""Open a window after its analysis directory finishes loading.
Args:
path: Recording or folder that was loaded.
sweep: Optional sweep to select.
spike_number: Optional spike to select.
analysis_dir: Completed analysis directory.
"""
try:
self.openSanPyWindow(
path,
sweep,
spike_number,
analysis_dir=analysis_dir,
)
except Exception as error:
logger.exception(f'Unable to open analysis window for "{path}"')
message = str(error) or type(error).__name__
self._onAnalysisDirLoadFailed(path, message)
def _onAnalysisDirLoadFailed(self, path: str, message: str) -> None:
"""Report an interactive analysis-directory load failure.
Args:
path: Recording or folder that failed to load.
message: User-facing failure detail.
"""
status = f'Unable to load "{path}": {message}'
self._openFirstWidget.slot_updateStatus(status)
QtWidgets.QMessageBox.warning(
self._openFirstWidget,
"Unable to Open",
status,
)
def _onAnalysisLoaderFinished(self) -> None:
"""Release the completed analysis loader thread."""
loader = self._analysisLoaderThread
self._analysisLoaderThread = None
if loader is not None:
loader.deleteLater()
def openSanPyWindow(
self,
path: str | os.PathLike[str] | None = None,
sweep: int | None = None,
spikeNumber: int | None = None,
*,
analysis_dir: sanpy.analysisDir | None = None,
) -> SanPyWindow | None:
"""Open or activate an analysis window for a recording or folder.
Args:
path: Recording or folder path, or None for an empty window.
sweep: Optional sweep to select when opening a recording.
spikeNumber: Optional spike to select when opening a recording.
analysis_dir: Preconstructed directory from an interactive worker.
Returns:
Newly created or existing analysis window, or None when ``path``
is an unsupported file.
"""
logger.info(f'path:{path}')
logger.info(f' sweep:{sweep}')
logger.info(f' spikeNumber:{spikeNumber}')
# Reject unsupported files before constructing an analysis window.
if path is not None and os.path.isfile(path):
if not self._is_supported_recording(path):
extension = pathlib.Path(path).suffix or "(no extension)"
message = (
f'SanPy cannot open files with the "{extension}" extension.'
)
logger.warning('%s Path: "%s"', message, path)
QtWidgets.QMessageBox.warning(
self._openFirstWidget,
"Unsupported File",
message,
)
return None
# 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,
analysis_dir=analysis_dir,
)
foundWindow.show()
foundWindow.raise_() # bring to front, raise is a python keyword
foundWindow.activateWindow() # bring to front
self._register_sanpy_window(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:
state = foundWindow.state
analysis = foundWindow.get_bAnalysis()
if state is not None and analysis is not None:
spike_sweep = int(
analysis.getSpikeStat([spikeNumber], "sweep")[0]
)
foundWindow.request_state(
WindowState(
state.file_key,
spike_sweep,
(spikeNumber,),
)
)
# add to recent opened windows
if path is not None:
self.getOptions().addPath(path)
# The launcher is reused rather than reconstructed, so refresh its
# cached tables after the successful open updates preferences.
self._openFirstWidget.refreshRecent()
self._openFirstWidget.slot_updateStatus("Ready")
# close the initial open first window
# logger.warning('todo: figure out how to close and garbage collect the _openFirstWidget properly')
self._openFirstWidget.hide()
# self._openFirstWidget.close()
#self._openFirstWidget = None
return foundWindow
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) -> None:
"""Show the About SanPy dialog.
The dialog body is the same widget as the SanPy Info left panel.
Close stays on the dialog.
"""
dlg = QtWidgets.QDialog()
dlg.setWindowTitle('About SanPy')
layout = QtWidgets.QVBoxLayout(dlg)
layout.addWidget(SanPyInfoWidget(self.sanpy_paths, dlg))
close_button = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Close)
close_button.rejected.connect(dlg.reject)
layout.addWidget(close_button)
dlg.exec()
|