|
| 1 | +from functools import wraps |
| 2 | +import sys |
| 3 | + |
| 4 | +from mantid.api import AnalysisDataServiceObserver |
| 5 | + |
| 6 | + |
| 7 | +def _catch_exceptions(func): |
| 8 | + """ |
| 9 | + Catch all exceptions in method and print a traceback to stderr |
| 10 | + """ |
| 11 | + |
| 12 | + @wraps(func) |
| 13 | + def wrapper(*args, **kwargs): |
| 14 | + try: |
| 15 | + func(*args, **kwargs) |
| 16 | + except Exception: |
| 17 | + sys.stderr.write("Error occurred in handler:\n") |
| 18 | + import traceback |
| 19 | + |
| 20 | + traceback.print_exc() |
| 21 | + |
| 22 | + return wrapper |
| 23 | + |
| 24 | + |
| 25 | +class MSliceADSObserver(AnalysisDataServiceObserver): |
| 26 | + def __init__(self, delete_callback, clear_callback, replace_callback, rename_callback): |
| 27 | + super(MSliceADSObserver, self).__init__() |
| 28 | + self.delete_callback = delete_callback |
| 29 | + self.clear_callback = clear_callback |
| 30 | + self.replace_callback = replace_callback |
| 31 | + self.rename_callback = rename_callback |
| 32 | + |
| 33 | + self.observeDelete(True) |
| 34 | + self.observeRename(True) |
| 35 | + self.observeReplace(True) |
| 36 | + self.observeClear(True) |
| 37 | + |
| 38 | + @_catch_exceptions |
| 39 | + def deleteHandle(self, workspace_name, workspace): |
| 40 | + """ |
| 41 | + Called when the ADS deletes a workspace, removes it from the dict of tracked workspaces. |
| 42 | + :param workspace_name: name of the workspace |
| 43 | + :param workspace: reference to the workspace (not used) |
| 44 | + """ |
| 45 | + self.delete_callback(workspace_name) |
| 46 | + |
| 47 | + @_catch_exceptions |
| 48 | + def renameHandle(self, old_workspace_name, new_workspace_name): |
| 49 | + """ |
| 50 | + Called when the ADS renames a workspace, updates the dict with the new name. |
| 51 | + :param old_workspace_name: original name of the workspace |
| 52 | + :param new_workspace_name: new name for the workspace |
| 53 | + """ |
| 54 | + self.rename_callback(old_workspace_name, new_workspace_name) |
| 55 | + |
| 56 | + @_catch_exceptions |
| 57 | + def clearHandle(self): |
| 58 | + """ |
| 59 | + Called when the ADS has been cleared, removes all data. |
| 60 | + """ |
| 61 | + self.clear_callback() |
| 62 | + |
| 63 | + @_catch_exceptions |
| 64 | + def replaceHandle(self, name, workspace): |
| 65 | + """ |
| 66 | + Called when the ADS has replaced a workspace with one of the same name. |
| 67 | + Updates the workspace stored in the dict. |
| 68 | + :param name: The name of the workspace. |
| 69 | + :param workspace: A reference to the new workspace |
| 70 | + """ |
| 71 | + self.replace_callback(name, workspace) |
| 72 | + |
| 73 | + def unsubscribe(self): |
| 74 | + self.observeDelete(False) |
| 75 | + self.observeRename(False) |
| 76 | + self.observeClear(False) |
| 77 | + self.observeReplace(False) |
0 commit comments