source: sasview/src/sas/qtgui/MainWindow/GuiManager.py @ e5ae812

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since e5ae812 was e5ae812, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 10 months ago

Added C&S tab serialization.

  • Property mode set to 100644
File size: 43.0 KB
Line 
1import sys
2import os
3import subprocess
4import logging
5import json
6import webbrowser
7import traceback
8
9from PyQt5.QtWidgets import *
10from PyQt5.QtGui import *
11from PyQt5.QtCore import Qt, QLocale, QUrl
12
13import matplotlib as mpl
14mpl.use("Qt5Agg")
15
16from twisted.internet import reactor
17# General SAS imports
18from sas import get_local_config, get_custom_config
19from sas.qtgui.Utilities.ConnectionProxy import ConnectionProxy
20from sas.qtgui.Utilities.SasviewLogger import setup_qt_logging
21
22import sas.qtgui.Utilities.LocalConfig as LocalConfig
23import sas.qtgui.Utilities.GuiUtils as GuiUtils
24
25import sas.qtgui.Utilities.ObjectLibrary as ObjectLibrary
26from sas.qtgui.Utilities.TabbedModelEditor import TabbedModelEditor
27from sas.qtgui.Utilities.PluginManager import PluginManager
28from sas.qtgui.Utilities.GridPanel import BatchOutputPanel
29from sas.qtgui.Utilities.ResultPanel import ResultPanel
30
31from sas.qtgui.Utilities.ReportDialog import ReportDialog
32from sas.qtgui.MainWindow.UI.AcknowledgementsUI import Ui_Acknowledgements
33from sas.qtgui.MainWindow.AboutBox import AboutBox
34from sas.qtgui.MainWindow.WelcomePanel import WelcomePanel
35from sas.qtgui.MainWindow.CategoryManager import CategoryManager
36
37from sas.qtgui.MainWindow.DataManager import DataManager
38
39from sas.qtgui.Calculators.SldPanel import SldPanel
40from sas.qtgui.Calculators.DensityPanel import DensityPanel
41from sas.qtgui.Calculators.KiessigPanel import KiessigPanel
42from sas.qtgui.Calculators.SlitSizeCalculator import SlitSizeCalculator
43from sas.qtgui.Calculators.GenericScatteringCalculator import GenericScatteringCalculator
44from sas.qtgui.Calculators.ResolutionCalculatorPanel import ResolutionCalculatorPanel
45from sas.qtgui.Calculators.DataOperationUtilityPanel import DataOperationUtilityPanel
46
47# Perspectives
48import sas.qtgui.Perspectives as Perspectives
49from sas.qtgui.Perspectives.Fitting.FittingPerspective import FittingWindow
50from sas.qtgui.MainWindow.DataExplorer import DataExplorerWindow, DEFAULT_PERSPECTIVE
51
52from sas.qtgui.Utilities.AddMultEditor import AddMultEditor
53from sas.qtgui.Utilities.ImageViewer import ImageViewer
54
55logger = logging.getLogger(__name__)
56
57class Acknowledgements(QDialog, Ui_Acknowledgements):
58    def __init__(self, parent=None):
59        QDialog.__init__(self, parent)
60        self.setupUi(self)
61
62class GuiManager(object):
63    """
64    Main SasView window functionality
65    """
66    def __init__(self, parent=None):
67        """
68        Initialize the manager as a child of MainWindow.
69        """
70        self._workspace = parent
71        self._parent = parent
72
73        # Decide on a locale
74        QLocale.setDefault(QLocale('en_US'))
75
76        # Redefine exception hook to not explicitly crash the app.
77        sys.excepthook = self.info
78
79        # Add signal callbacks
80        self.addCallbacks()
81
82        # Assure model categories are available
83        self.addCategories()
84
85        # Create the data manager
86        # TODO: pull out all required methods from DataManager and reimplement
87        self._data_manager = DataManager()
88
89        # Create action triggers
90        self.addTriggers()
91
92        # Currently displayed perspective
93        self._current_perspective = None
94
95        # Populate the main window with stuff
96        self.addWidgets()
97
98        # Fork off logging messages to the Log Window
99        handler = setup_qt_logging()
100        handler.messageWritten.connect(self.appendLog)
101
102        # Log the start of the session
103        logging.info(" --- SasView session started ---")
104        # Log the python version
105        logging.info("Python: %s" % sys.version)
106
107        # Set up the status bar
108        self.statusBarSetup()
109
110        # Current tutorial location
111        self._tutorialLocation = os.path.abspath(os.path.join(GuiUtils.HELP_DIRECTORY_LOCATION,
112                                              "_downloads",
113                                              "Tutorial.pdf"))
114
115    def info(self, type, value, tb):
116        logger.error("SasView threw exception: " + str(value))
117        traceback.print_exception(type, value, tb)
118
119    def addWidgets(self):
120        """
121        Populate the main window with widgets
122
123        TODO: overwrite close() on Log and DR widgets so they can be hidden/shown
124        on request
125        """
126        # Add FileDialog widget as docked
127        self.filesWidget = DataExplorerWindow(self._parent, self, manager=self._data_manager)
128        ObjectLibrary.addObject('DataExplorer', self.filesWidget)
129
130        self.dockedFilesWidget = QDockWidget("Data Explorer", self._workspace)
131        self.dockedFilesWidget.setFloating(False)
132        self.dockedFilesWidget.setWidget(self.filesWidget)
133
134        # Modify menu items on widget visibility change
135        self.dockedFilesWidget.visibilityChanged.connect(self.updateContextMenus)
136
137        self._workspace.addDockWidget(Qt.LeftDockWidgetArea, self.dockedFilesWidget)
138        self._workspace.resizeDocks([self.dockedFilesWidget], [305], Qt.Horizontal)
139
140        # Add the console window as another docked widget
141        self.logDockWidget = QDockWidget("Log Explorer", self._workspace)
142        self.logDockWidget.setObjectName("LogDockWidget")
143        self.logDockWidget.visibilityChanged.connect(self.updateLogContextMenus)
144
145
146        self.listWidget = QTextBrowser()
147        self.logDockWidget.setWidget(self.listWidget)
148        self._workspace.addDockWidget(Qt.BottomDockWidgetArea, self.logDockWidget)
149
150        # Add other, minor widgets
151        self.ackWidget = Acknowledgements()
152        self.aboutWidget = AboutBox()
153        self.categoryManagerWidget = CategoryManager(self._parent, manager=self)
154
155        self.grid_window = None
156        self.grid_window = BatchOutputPanel(parent=self)
157        if sys.platform == "darwin":
158            self.grid_window.menubar.setNativeMenuBar(False)
159        self.grid_subwindow = self._workspace.workspace.addSubWindow(self.grid_window)
160        self.grid_subwindow.setVisible(False)
161        self.grid_window.windowClosedSignal.connect(lambda: self.grid_subwindow.setVisible(False))
162
163        self.results_panel = ResultPanel(parent=self._parent, manager=self)
164        self.results_frame = self._workspace.workspace.addSubWindow(self.results_panel)
165        self.results_frame.setVisible(False)
166        self.results_panel.windowClosedSignal.connect(lambda: self.results_frame.setVisible(False))
167
168        self._workspace.toolBar.setVisible(LocalConfig.TOOLBAR_SHOW)
169        self._workspace.actionHide_Toolbar.setText("Show Toolbar")
170
171        # Add calculators - floating for usability
172        self.SLDCalculator = SldPanel(self)
173        self.DVCalculator = DensityPanel(self)
174        self.KIESSIGCalculator = KiessigPanel(self)
175        self.SlitSizeCalculator = SlitSizeCalculator(self)
176        self.GENSASCalculator = GenericScatteringCalculator(self)
177        self.ResolutionCalculator = ResolutionCalculatorPanel(self)
178        self.DataOperation = DataOperationUtilityPanel(self)
179
180    def addCategories(self):
181        """
182        Make sure categories.json exists and if not compile it and install in ~/.sasview
183        """
184        try:
185            from sas.sascalc.fit.models import ModelManager
186            from sas.qtgui.Utilities.CategoryInstaller import CategoryInstaller
187            model_list = ModelManager().cat_model_list()
188            CategoryInstaller.check_install(model_list=model_list)
189        except Exception:
190            import traceback
191            logger.error("%s: could not load SasView models")
192            logger.error(traceback.format_exc())
193
194    def updateLogContextMenus(self, visible=False):
195        """
196        Modify the View/Data Explorer menu item text on widget visibility
197        """
198        if visible:
199            self._workspace.actionHide_LogExplorer.setText("Hide Log Explorer")
200        else:
201            self._workspace.actionHide_LogExplorer.setText("Show Log Explorer")
202
203    def updateContextMenus(self, visible=False):
204        """
205        Modify the View/Data Explorer menu item text on widget visibility
206        """
207        if visible:
208            self._workspace.actionHide_DataExplorer.setText("Hide Data Explorer")
209        else:
210            self._workspace.actionHide_DataExplorer.setText("Show Data Explorer")
211
212    def statusBarSetup(self):
213        """
214        Define the status bar.
215        | <message label> .... | Progress Bar |
216
217        Progress bar invisible until explicitly shown
218        """
219        self.progress = QProgressBar()
220        self._workspace.statusbar.setSizeGripEnabled(False)
221
222        self.statusLabel = QLabel()
223        self.statusLabel.setText("Welcome to SasView")
224        self._workspace.statusbar.addPermanentWidget(self.statusLabel, 1)
225        self._workspace.statusbar.addPermanentWidget(self.progress, stretch=0)
226        self.progress.setRange(0, 100)
227        self.progress.setValue(0)
228        self.progress.setTextVisible(True)
229        self.progress.setVisible(False)
230
231    def fileWasRead(self, data):
232        """
233        Callback for fileDataReceivedSignal
234        """
235        pass
236
237    def showHelp(self, url):
238        """
239        Open a local url in the default browser
240        """
241        GuiUtils.showHelp(url)
242
243    def workspace(self):
244        """
245        Accessor for the main window workspace
246        """
247        return self._workspace.workspace
248
249    def perspectiveChanged(self, perspective_name):
250        """
251        Respond to change of the perspective signal
252        """
253        # Close the previous perspective
254        self.clearPerspectiveMenubarOptions(self._current_perspective)
255        if self._current_perspective:
256            self._current_perspective.setClosable()
257            self._current_perspective.close()
258            self._workspace.workspace.removeSubWindow(self._current_perspective)
259        # Default perspective
260        self._current_perspective = Perspectives.PERSPECTIVES[str(perspective_name)](parent=self)
261
262        self.setupPerspectiveMenubarOptions(self._current_perspective)
263
264        subwindow = self._workspace.workspace.addSubWindow(self._current_perspective)
265
266        # Resize to the workspace height
267        workspace_height = self._workspace.workspace.sizeHint().height()
268        perspective_size = self._current_perspective.sizeHint()
269        perspective_width = perspective_size.width()
270        self._current_perspective.resize(perspective_width, workspace_height-10)
271
272        self._current_perspective.show()
273
274    def updatePerspective(self, data):
275        """
276        Update perspective with data sent.
277        """
278        assert isinstance(data, list)
279        if self._current_perspective is not None:
280            self._current_perspective.setData(list(data.values()))
281        else:
282            msg = "No perspective is currently active."
283            logging.info(msg)
284
285    def communicator(self):
286        """ Accessor for the communicator """
287        return self.communicate
288
289    def perspective(self):
290        """ Accessor for the perspective """
291        return self._current_perspective
292
293    def updateProgressBar(self, value):
294        """
295        Update progress bar with the required value (0-100)
296        """
297        assert -1 <= value <= 100
298        if value == -1:
299            self.progress.setVisible(False)
300            return
301        if not self.progress.isVisible():
302            self.progress.setTextVisible(True)
303            self.progress.setVisible(True)
304
305        self.progress.setValue(value)
306
307    def updateStatusBar(self, text):
308        """
309        Set the status bar text
310        """
311        self.statusLabel.setText(text)
312
313    def appendLog(self, msg):
314        """Appends a message to the list widget in the Log Explorer. Use this
315        instead of listWidget.insertPlainText() to facilitate auto-scrolling"""
316        self.listWidget.append(msg.strip())
317
318    def createGuiData(self, item, p_file=None):
319        """
320        Access the Data1D -> plottable Data1D conversion
321        """
322        return self._data_manager.create_gui_data(item, p_file)
323
324    def setData(self, data):
325        """
326        Sends data to current perspective
327        """
328        if self._current_perspective is not None:
329            self._current_perspective.setData(list(data.values()))
330        else:
331            msg = "Guiframe does not have a current perspective"
332            logging.info(msg)
333
334    def findItemFromFilename(self, filename):
335        """
336        Queries the data explorer for the index corresponding to the filename within
337        """
338        return self.filesWidget.itemFromFilename(filename)
339
340    def quitApplication(self):
341        """
342        Close the reactor and exit nicely.
343        """
344        # Display confirmation messagebox
345        quit_msg = "Are you sure you want to exit the application?"
346        reply = QMessageBox.question(
347            self._parent,
348            'Information',
349            quit_msg,
350            QMessageBox.Yes,
351            QMessageBox.No)
352
353        # Exit if yes
354        if reply == QMessageBox.Yes:
355            # save the paths etc.
356            self.saveCustomConfig()
357            reactor.callFromThread(reactor.stop)
358            return True
359
360        return False
361
362    def checkUpdate(self):
363        """
364        Check with the deployment server whether a new version
365        of the application is available.
366        A thread is started for the connecting with the server. The thread calls
367        a call-back method when the current version number has been obtained.
368        """
369        version_info = {"version": "0.0.0"}
370        c = ConnectionProxy(LocalConfig.__update_URL__, LocalConfig.UPDATE_TIMEOUT)
371        response = c.connect()
372        if response is None:
373            return
374        try:
375            content = response.read().strip()
376            logging.info("Connected to www.sasview.org. Latest version: %s"
377                            % (content))
378            version_info = json.loads(content)
379            self.processVersion(version_info)
380        except ValueError as ex:
381            logging.info("Failed to connect to www.sasview.org:", ex)
382
383    def processVersion(self, version_info):
384        """
385        Call-back method for the process of checking for updates.
386        This methods is called by a VersionThread object once the current
387        version number has been obtained. If the check is being done in the
388        background, the user will not be notified unless there's an update.
389
390        :param version: version string
391        """
392        try:
393            version = version_info["version"]
394            if version == "0.0.0":
395                msg = "Could not connect to the application server."
396                msg += " Please try again later."
397                self.communicate.statusBarUpdateSignal.emit(msg)
398
399            elif version.__gt__(LocalConfig.__version__):
400                msg = "Version %s is available! " % str(version)
401                if "download_url" in version_info:
402                    webbrowser.open(version_info["download_url"])
403                else:
404                    webbrowser.open(LocalConfig.__download_page__)
405                self.communicate.statusBarUpdateSignal.emit(msg)
406            else:
407                msg = "You have the latest version"
408                msg += " of %s" % str(LocalConfig.__appname__)
409                self.communicate.statusBarUpdateSignal.emit(msg)
410        except:
411            msg = "guiframe: could not get latest application"
412            msg += " version number\n  %s" % sys.exc_info()[1]
413            logging.error(msg)
414            msg = "Could not connect to the application server."
415            msg += " Please try again later."
416            self.communicate.statusBarUpdateSignal.emit(msg)
417
418    def actionWelcome(self):
419        """ Show the Welcome panel """
420        self.welcomePanel = WelcomePanel()
421        self._workspace.workspace.addSubWindow(self.welcomePanel)
422        self.welcomePanel.show()
423
424    def showWelcomeMessage(self):
425        """ Show the Welcome panel, when required """
426        # Assure the welcome screen is requested
427        show_welcome_widget = True
428        custom_config = get_custom_config()
429        if hasattr(custom_config, "WELCOME_PANEL_SHOW"):
430            if isinstance(custom_config.WELCOME_PANEL_SHOW, bool):
431                show_welcome_widget = custom_config.WELCOME_PANEL_SHOW
432            else:
433                logging.warning("WELCOME_PANEL_SHOW has invalid value in custom_config.py")
434        if show_welcome_widget:
435            self.actionWelcome()
436
437    def addCallbacks(self):
438        """
439        Method defining all signal connections for the gui manager
440        """
441        self.communicate = GuiUtils.Communicate()
442        self.communicate.fileDataReceivedSignal.connect(self.fileWasRead)
443        self.communicate.statusBarUpdateSignal.connect(self.updateStatusBar)
444        self.communicate.updatePerspectiveWithDataSignal.connect(self.updatePerspective)
445        self.communicate.progressBarUpdateSignal.connect(self.updateProgressBar)
446        self.communicate.perspectiveChangedSignal.connect(self.perspectiveChanged)
447        self.communicate.updateTheoryFromPerspectiveSignal.connect(self.updateTheoryFromPerspective)
448        self.communicate.deleteIntermediateTheoryPlotsSignal.connect(self.deleteIntermediateTheoryPlotsByModelID)
449        self.communicate.plotRequestedSignal.connect(self.showPlot)
450        self.communicate.plotFromFilenameSignal.connect(self.showPlotFromFilename)
451        self.communicate.updateModelFromDataOperationPanelSignal.connect(self.updateModelFromDataOperationPanel)
452
453    def addTriggers(self):
454        """
455        Trigger definitions for all menu/toolbar actions.
456        """
457        # disable not yet fully implemented actions
458        self._workspace.actionUndo.setVisible(False)
459        self._workspace.actionRedo.setVisible(False)
460        self._workspace.actionReset.setVisible(False)
461        self._workspace.actionStartup_Settings.setVisible(False)
462        #self._workspace.actionImage_Viewer.setVisible(False)
463        self._workspace.actionCombine_Batch_Fit.setVisible(False)
464        # orientation viewer set to invisible SASVIEW-1132
465        self._workspace.actionOrientation_Viewer.setVisible(False)
466
467        # File
468        self._workspace.actionLoadData.triggered.connect(self.actionLoadData)
469        self._workspace.actionLoad_Data_Folder.triggered.connect(self.actionLoad_Data_Folder)
470        self._workspace.actionOpen_Project.triggered.connect(self.actionOpen_Project)
471        self._workspace.actionOpen_Analysis.triggered.connect(self.actionOpen_Analysis)
472        self._workspace.actionSave.triggered.connect(self.actionSave_Project)
473        self._workspace.actionSave_Analysis.triggered.connect(self.actionSave_Analysis)
474        self._workspace.actionQuit.triggered.connect(self.actionQuit)
475        # Edit
476        self._workspace.actionUndo.triggered.connect(self.actionUndo)
477        self._workspace.actionRedo.triggered.connect(self.actionRedo)
478        self._workspace.actionCopy.triggered.connect(self.actionCopy)
479        self._workspace.actionPaste.triggered.connect(self.actionPaste)
480        self._workspace.actionReport.triggered.connect(self.actionReport)
481        self._workspace.actionReset.triggered.connect(self.actionReset)
482        self._workspace.actionExcel.triggered.connect(self.actionExcel)
483        self._workspace.actionLatex.triggered.connect(self.actionLatex)
484        # View
485        self._workspace.actionShow_Grid_Window.triggered.connect(self.actionShow_Grid_Window)
486        self._workspace.actionHide_Toolbar.triggered.connect(self.actionHide_Toolbar)
487        self._workspace.actionStartup_Settings.triggered.connect(self.actionStartup_Settings)
488        self._workspace.actionCategory_Manager.triggered.connect(self.actionCategory_Manager)
489        self._workspace.actionHide_DataExplorer.triggered.connect(self.actionHide_DataExplorer)
490        self._workspace.actionHide_LogExplorer.triggered.connect(self.actionHide_LogExplorer)
491        # Tools
492        self._workspace.actionData_Operation.triggered.connect(self.actionData_Operation)
493        self._workspace.actionSLD_Calculator.triggered.connect(self.actionSLD_Calculator)
494        self._workspace.actionDensity_Volume_Calculator.triggered.connect(self.actionDensity_Volume_Calculator)
495        self._workspace.actionKeissig_Calculator.triggered.connect(self.actionKiessig_Calculator)
496        #self._workspace.actionKIESSING_Calculator.triggered.connect(self.actionKIESSING_Calculator)
497        self._workspace.actionSlit_Size_Calculator.triggered.connect(self.actionSlit_Size_Calculator)
498        self._workspace.actionSAS_Resolution_Estimator.triggered.connect(self.actionSAS_Resolution_Estimator)
499        self._workspace.actionGeneric_Scattering_Calculator.triggered.connect(self.actionGeneric_Scattering_Calculator)
500        self._workspace.actionPython_Shell_Editor.triggered.connect(self.actionPython_Shell_Editor)
501        self._workspace.actionImage_Viewer.triggered.connect(self.actionImage_Viewer)
502        self._workspace.actionOrientation_Viewer.triggered.connect(self.actionOrientation_Viewer)
503        self._workspace.actionFreeze_Theory.triggered.connect(self.actionFreeze_Theory)
504        # Fitting
505        self._workspace.actionNew_Fit_Page.triggered.connect(self.actionNew_Fit_Page)
506        self._workspace.actionConstrained_Fit.triggered.connect(self.actionConstrained_Fit)
507        self._workspace.actionCombine_Batch_Fit.triggered.connect(self.actionCombine_Batch_Fit)
508        self._workspace.actionFit_Options.triggered.connect(self.actionFit_Options)
509        self._workspace.actionGPU_Options.triggered.connect(self.actionGPU_Options)
510        self._workspace.actionFit_Results.triggered.connect(self.actionFit_Results)
511        self._workspace.actionAdd_Custom_Model.triggered.connect(self.actionAdd_Custom_Model)
512        self._workspace.actionEdit_Custom_Model.triggered.connect(self.actionEdit_Custom_Model)
513        self._workspace.actionManage_Custom_Models.triggered.connect(self.actionManage_Custom_Models)
514        self._workspace.actionAddMult_Models.triggered.connect(self.actionAddMult_Models)
515        self._workspace.actionEditMask.triggered.connect(self.actionEditMask)
516
517        # Window
518        self._workspace.actionCascade.triggered.connect(self.actionCascade)
519        self._workspace.actionTile.triggered.connect(self.actionTile)
520        self._workspace.actionArrange_Icons.triggered.connect(self.actionArrange_Icons)
521        self._workspace.actionNext.triggered.connect(self.actionNext)
522        self._workspace.actionPrevious.triggered.connect(self.actionPrevious)
523        self._workspace.actionClosePlots.triggered.connect(self.actionClosePlots)
524        # Analysis
525        self._workspace.actionFitting.triggered.connect(self.actionFitting)
526        self._workspace.actionInversion.triggered.connect(self.actionInversion)
527        self._workspace.actionInvariant.triggered.connect(self.actionInvariant)
528        self._workspace.actionCorfunc.triggered.connect(self.actionCorfunc)
529        # Help
530        self._workspace.actionDocumentation.triggered.connect(self.actionDocumentation)
531        self._workspace.actionTutorial.triggered.connect(self.actionTutorial)
532        self._workspace.actionAcknowledge.triggered.connect(self.actionAcknowledge)
533        self._workspace.actionAbout.triggered.connect(self.actionAbout)
534        self._workspace.actionWelcomeWidget.triggered.connect(self.actionWelcome)
535        self._workspace.actionCheck_for_update.triggered.connect(self.actionCheck_for_update)
536
537        self.communicate.sendDataToGridSignal.connect(self.showBatchOutput)
538        self.communicate.resultPlotUpdateSignal.connect(self.showFitResults)
539
540    #============ FILE =================
541    def actionLoadData(self):
542        """
543        Menu File/Load Data File(s)
544        """
545        self.filesWidget.loadFile()
546
547    def actionLoad_Data_Folder(self):
548        """
549        Menu File/Load Data Folder
550        """
551        self.filesWidget.loadFolder()
552
553    def actionOpen_Project(self):
554        """
555        Menu Open Project
556        """
557        self.filesWidget.loadProject()
558
559    def actionOpen_Analysis(self):
560        """
561        """
562        self.filesWidget.loadAnalysis()
563        pass
564
565    def actionSave_Project(self):
566        """
567        Menu Save Project
568        """
569        filename = self.filesWidget.saveProject()
570
571        # datasets
572        all_data = self.filesWidget.getAllData()
573
574        # fit tabs
575        params={}
576        perspective = self.perspective()
577        if hasattr(perspective, 'isSerializable') and perspective.isSerializable():
578            params = perspective.serializeAllFitpage()
579
580        # project dictionary structure:
581        # analysis[data.id] = [{"fit_data":[data, checkbox, child data],
582        #                       "fit_params":[fitpage_state]}
583        # "fit_params" not present if dataset not sent to fitting
584        analysis = {}
585
586        for id, data in all_data.items():
587            if id=='is_batch':
588                analysis['is_batch'] = data
589                continue
590            data_content = {"fit_data":data}
591            if id in params.keys():
592                # this dataset is represented also by the fit tab. Add to it.
593                data_content["fit_params"] = params[id]
594            analysis[id] = data_content
595
596        # standalone constraint pages
597        for keys, values in params.items():
598            if not 'is_constraint' in values[0]:
599                continue
600            analysis[keys] = values[0]
601
602        with open(filename, 'w') as outfile:
603            GuiUtils.saveData(outfile, analysis)
604
605    def actionSave_Analysis(self):
606        """
607        Menu File/Save Analysis
608        """
609        per = self.perspective()
610        if not isinstance(per, FittingWindow):
611            return
612        # get fit page serialization
613        params = per.serializeCurrentFitpage()
614        # Find dataset ids for the current tab
615        # (can be multiple, if batch)
616        data_id = per.currentTabDataId()
617        tab_id = per.currentTab.tab_id
618        analysis = {}
619        for id in data_id:
620            an = {}
621            data_for_id = self.filesWidget.getDataForID(id)
622            an['fit_data'] = data_for_id
623            an['fit_params'] = [params]
624            analysis[id] = an
625
626        self.filesWidget.saveAnalysis(analysis, tab_id)
627
628    def actionQuit(self):
629        """
630        Close the reactor, exit the application.
631        """
632        self.quitApplication()
633
634    #============ EDIT =================
635    def actionUndo(self):
636        """
637        """
638        print("actionUndo TRIGGERED")
639        pass
640
641    def actionRedo(self):
642        """
643        """
644        print("actionRedo TRIGGERED")
645        pass
646
647    def actionCopy(self):
648        """
649        Send a signal to the fitting perspective so parameters
650        can be saved to the clipboard
651        """
652        self.communicate.copyFitParamsSignal.emit("")
653        self._workspace.actionPaste.setEnabled(True)
654        pass
655
656    def actionPaste(self):
657        """
658        Send a signal to the fitting perspective so parameters
659        from the clipboard can be used to modify the fit state
660        """
661        self.communicate.pasteFitParamsSignal.emit()
662
663    def actionReport(self):
664        """
665        Show the Fit Report dialog.
666        """
667        report_list = None
668        if getattr(self._current_perspective, "currentTab"):
669            try:
670                report_list = self._current_perspective.currentTab.getReport()
671            except Exception as ex:
672                logging.error("Report generation failed with: " + str(ex))
673
674        if report_list is not None:
675            self.report_dialog = ReportDialog(parent=self, report_list=report_list)
676            self.report_dialog.show()
677
678    def actionReset(self):
679        """
680        """
681        logging.warning(" *** actionOpen_Analysis logging *******")
682        print("actionReset print TRIGGERED")
683        sys.stderr.write("STDERR - TRIGGERED")
684        pass
685
686    def actionExcel(self):
687        """
688        Send a signal to the fitting perspective so parameters
689        can be saved to the clipboard
690        """
691        self.communicate.copyExcelFitParamsSignal.emit("Excel")
692
693    def actionLatex(self):
694        """
695        Send a signal to the fitting perspective so parameters
696        can be saved to the clipboard
697        """
698        self.communicate.copyLatexFitParamsSignal.emit("Latex")
699
700    #============ VIEW =================
701    def actionShow_Grid_Window(self):
702        """
703        """
704        self.showBatchOutput(None)
705
706    def showBatchOutput(self, output_data):
707        """
708        Display/redisplay the batch fit viewer
709        """
710        self.grid_subwindow.setVisible(True)
711        if output_data:
712            self.grid_window.addFitResults(output_data)
713
714    def actionHide_Toolbar(self):
715        """
716        Toggle toolbar vsibility
717        """
718        if self._workspace.toolBar.isVisible():
719            self._workspace.actionHide_Toolbar.setText("Show Toolbar")
720            self._workspace.toolBar.setVisible(False)
721        else:
722            self._workspace.actionHide_Toolbar.setText("Hide Toolbar")
723            self._workspace.toolBar.setVisible(True)
724        pass
725
726    def actionHide_DataExplorer(self):
727        """
728        Toggle Data Explorer vsibility
729        """
730        if self.dockedFilesWidget.isVisible():
731            self.dockedFilesWidget.setVisible(False)
732        else:
733            self.dockedFilesWidget.setVisible(True)
734        pass
735
736    def actionHide_LogExplorer(self):
737        """
738        Toggle Data Explorer vsibility
739        """
740        if self.logDockWidget.isVisible():
741            self.logDockWidget.setVisible(False)
742        else:
743            self.logDockWidget.setVisible(True)
744        pass
745
746    def actionStartup_Settings(self):
747        """
748        """
749        print("actionStartup_Settings TRIGGERED")
750        pass
751
752    def actionCategory_Manager(self):
753        """
754        """
755        self.categoryManagerWidget.show()
756
757    #============ TOOLS =================
758    def actionData_Operation(self):
759        """
760        """
761        self.communicate.sendDataToPanelSignal.emit(self._data_manager.get_all_data())
762
763        self.DataOperation.show()
764
765    def actionSLD_Calculator(self):
766        """
767        """
768        self.SLDCalculator.show()
769
770    def actionDensity_Volume_Calculator(self):
771        """
772        """
773        self.DVCalculator.show()
774
775    def actionKiessig_Calculator(self):
776        """
777        """
778        self.KIESSIGCalculator.show()
779
780    def actionSlit_Size_Calculator(self):
781        """
782        """
783        self.SlitSizeCalculator.show()
784
785    def actionSAS_Resolution_Estimator(self):
786        """
787        """
788        try:
789            self.ResolutionCalculator.show()
790        except Exception as ex:
791            logging.error(str(ex))
792            return
793
794    def actionGeneric_Scattering_Calculator(self):
795        """
796        """
797        try:
798            self.GENSASCalculator.show()
799        except Exception as ex:
800            logging.error(str(ex))
801            return
802
803    def actionPython_Shell_Editor(self):
804        """
805        Display the Jupyter console as a docked widget.
806        """
807        # Import moved here for startup performance reasons
808        from sas.qtgui.Utilities.IPythonWidget import IPythonWidget
809        terminal = IPythonWidget()
810
811        # Add the console window as another docked widget
812        self.ipDockWidget = QDockWidget("IPython", self._workspace)
813        self.ipDockWidget.setObjectName("IPythonDockWidget")
814        self.ipDockWidget.setWidget(terminal)
815        self._workspace.addDockWidget(Qt.RightDockWidgetArea, self.ipDockWidget)
816
817    def actionFreeze_Theory(self):
818        """
819        Convert a child index with data into a separate top level dataset
820        """
821        self.filesWidget.freezeCheckedData()
822
823    def actionOrientation_Viewer(self):
824        """
825        Make sasmodels orientation & jitter viewer available
826        """
827        from sasmodels.jitter import run as orientation_run
828        try:
829            orientation_run()
830        except Exception as ex:
831            logging.error(str(ex))
832
833    def actionImage_Viewer(self):
834        """
835        """
836        try:
837            self.image_viewer = ImageViewer(self)
838            if sys.platform == "darwin":
839                self.image_viewer.menubar.setNativeMenuBar(False)
840            self.image_viewer.show()
841        except Exception as ex:
842            logging.error(str(ex))
843            return
844
845    #============ FITTING =================
846    def actionNew_Fit_Page(self):
847        """
848        Add a new, empty Fit page in the fitting perspective.
849        """
850        # Make sure the perspective is correct
851        per = self.perspective()
852        if not isinstance(per, FittingWindow):
853            return
854        per.addFit(None)
855
856    def actionConstrained_Fit(self):
857        """
858        Add a new Constrained and Simult. Fit page in the fitting perspective.
859        """
860        per = self.perspective()
861        if not isinstance(per, FittingWindow):
862            return
863        per.addConstraintTab()
864
865    def actionCombine_Batch_Fit(self):
866        """
867        """
868        print("actionCombine_Batch_Fit TRIGGERED")
869        pass
870
871    def actionFit_Options(self):
872        """
873        """
874        if getattr(self._current_perspective, "fit_options_widget"):
875            self._current_perspective.fit_options_widget.show()
876        pass
877
878    def actionGPU_Options(self):
879        """
880        Load the OpenCL selection dialog if the fitting perspective is active
881        """
882        if hasattr(self._current_perspective, "gpu_options_widget"):
883            self._current_perspective.gpu_options_widget.show()
884        pass
885
886    def actionFit_Results(self):
887        """
888        """
889        self.showFitResults(None)
890
891    def showFitResults(self, output_data):
892        """
893        Show bumps convergence plots
894        """
895        self.results_frame.setVisible(True)
896        if output_data:
897            self.results_panel.onPlotResults(output_data, optimizer=self.perspective().optimizer)
898
899    def actionAdd_Custom_Model(self):
900        """
901        """
902        self.model_editor = TabbedModelEditor(self)
903        self.model_editor.show()
904
905    def actionEdit_Custom_Model(self):
906        """
907        """
908        self.model_editor = TabbedModelEditor(self, edit_only=True)
909        self.model_editor.show()
910
911    def actionManage_Custom_Models(self):
912        """
913        """
914        self.model_manager = PluginManager(self)
915        self.model_manager.show()
916
917    def actionAddMult_Models(self):
918        """
919        """
920        # Add Simple Add/Multiply Editor
921        self.add_mult_editor = AddMultEditor(self)
922        self.add_mult_editor.show()
923
924    def actionEditMask(self):
925
926        self.communicate.extMaskEditorSignal.emit()
927
928    #============ ANALYSIS =================
929    def actionFitting(self):
930        """
931        Change to the Fitting perspective
932        """
933        self.perspectiveChanged("Fitting")
934        # Notify other widgets
935        self.filesWidget.onAnalysisUpdate("Fitting")
936
937    def actionInversion(self):
938        """
939        Change to the Inversion perspective
940        """
941        self.perspectiveChanged("Inversion")
942        self.filesWidget.onAnalysisUpdate("Inversion")
943
944    def actionInvariant(self):
945        """
946        Change to the Invariant perspective
947        """
948        self.perspectiveChanged("Invariant")
949        self.filesWidget.onAnalysisUpdate("Invariant")
950
951    def actionCorfunc(self):
952        """
953        Change to the Corfunc perspective
954        """
955        self.perspectiveChanged("Corfunc")
956        self.filesWidget.onAnalysisUpdate("Corfunc")
957
958    #============ WINDOW =================
959    def actionCascade(self):
960        """
961        Arranges all the child windows in a cascade pattern.
962        """
963        self._workspace.workspace.cascadeSubWindows()
964
965    def actionTile(self):
966        """
967        Tile workspace windows
968        """
969        self._workspace.workspace.tileSubWindows()
970
971    def actionArrange_Icons(self):
972        """
973        Arranges all iconified windows at the bottom of the workspace
974        """
975        self._workspace.workspace.arrangeIcons()
976
977    def actionNext(self):
978        """
979        Gives the input focus to the next window in the list of child windows.
980        """
981        self._workspace.workspace.activateNextSubWindow()
982
983    def actionPrevious(self):
984        """
985        Gives the input focus to the previous window in the list of child windows.
986        """
987        self._workspace.workspace.activatePreviousSubWindow()
988
989    def actionClosePlots(self):
990        """
991        Closes all Plotters and Plotter2Ds.
992        """
993        self.filesWidget.closeAllPlots()
994        pass
995
996    #============ HELP =================
997    def actionDocumentation(self):
998        """
999        Display the documentation
1000
1001        TODO: use QNetworkAccessManager to assure _helpLocation is valid
1002        """
1003        helpfile = "/index.html"
1004        self.showHelp(helpfile)
1005
1006    def actionTutorial(self):
1007        """
1008        Open the tutorial PDF file with default PDF renderer
1009        """
1010        # Not terribly safe here. Shell injection warning.
1011        # isfile() helps but this probably needs a better solution.
1012        if os.path.isfile(self._tutorialLocation):
1013            result = subprocess.Popen([self._tutorialLocation], shell=True)
1014
1015    def actionAcknowledge(self):
1016        """
1017        Open the Acknowledgements widget
1018        """
1019        self.ackWidget.show()
1020
1021    def actionAbout(self):
1022        """
1023        Open the About box
1024        """
1025        # Update the about box with current version and stuff
1026
1027        # TODO: proper sizing
1028        self.aboutWidget.show()
1029
1030    def actionCheck_for_update(self):
1031        """
1032        Menu Help/Check for Update
1033        """
1034        self.checkUpdate()
1035
1036    def updateTheoryFromPerspective(self, index):
1037        """
1038        Catch the theory update signal from a perspective
1039        Send the request to the DataExplorer for updating the theory model.
1040        """
1041        self.filesWidget.updateTheoryFromPerspective(index)
1042
1043    def deleteIntermediateTheoryPlotsByModelID(self, model_id):
1044        """
1045        Catch the signal to delete items in the Theory item model which correspond to a model ID.
1046        Send the request to the DataExplorer for updating the theory model.
1047        """
1048        self.filesWidget.deleteIntermediateTheoryPlotsByModelID(model_id)
1049
1050    def updateModelFromDataOperationPanel(self, new_item, new_datalist_item):
1051        """
1052        :param new_item: item to be added to list of loaded files
1053        :param new_datalist_item:
1054        """
1055        if not isinstance(new_item, QStandardItem) or \
1056                not isinstance(new_datalist_item, dict):
1057            msg = "Wrong data type returned from calculations."
1058            raise AttributeError(msg)
1059
1060        self.filesWidget.model.appendRow(new_item)
1061        self._data_manager.add_data(new_datalist_item)
1062
1063    def showPlotFromFilename(self, filename):
1064        """
1065        Pass the show plot request to the data explorer
1066        """
1067        if hasattr(self, "filesWidget"):
1068            self.filesWidget.displayFile(filename=filename, is_data=True)
1069
1070    def showPlot(self, plot, id):
1071        """
1072        Pass the show plot request to the data explorer
1073        """
1074        if hasattr(self, "filesWidget"):
1075            self.filesWidget.displayData(plot, id)
1076
1077    def uncheckAllMenuItems(self, menuObject):
1078        """
1079        Uncheck all options in a given menu
1080        """
1081        menuObjects = menuObject.actions()
1082
1083        for menuItem in menuObjects:
1084            menuItem.setChecked(False)
1085
1086    def checkAnalysisOption(self, analysisMenuOption):
1087        """
1088        Unchecks all the items in the analysis menu and checks the item passed
1089        """
1090        self.uncheckAllMenuItems(self._workspace.menuAnalysis)
1091        analysisMenuOption.setChecked(True)
1092
1093    def clearPerspectiveMenubarOptions(self, perspective):
1094        """
1095        When closing a perspective, clears the menu bar
1096        """
1097        for menuItem in self._workspace.menuAnalysis.actions():
1098            menuItem.setChecked(False)
1099
1100        if isinstance(self._current_perspective, Perspectives.PERSPECTIVES["Fitting"]):
1101            self._workspace.menubar.removeAction(self._workspace.menuFitting.menuAction())
1102
1103    def setupPerspectiveMenubarOptions(self, perspective):
1104        """
1105        When setting a perspective, sets up the menu bar
1106        """
1107        self._workspace.actionReport.setEnabled(False)
1108        self._workspace.actionOpen_Analysis.setEnabled(False)
1109        self._workspace.actionSave_Analysis.setEnabled(False)
1110        if hasattr(perspective, 'isSerializable') and perspective.isSerializable():
1111            self._workspace.actionOpen_Analysis.setEnabled(True)
1112            self._workspace.actionSave_Analysis.setEnabled(True)
1113
1114        if isinstance(perspective, Perspectives.PERSPECTIVES["Fitting"]):
1115            self.checkAnalysisOption(self._workspace.actionFitting)
1116            # Put the fitting menu back in
1117            # This is a bit involved but it is needed to preserve the menu ordering
1118            self._workspace.menubar.removeAction(self._workspace.menuWindow.menuAction())
1119            self._workspace.menubar.removeAction(self._workspace.menuHelp.menuAction())
1120            self._workspace.menubar.addAction(self._workspace.menuFitting.menuAction())
1121            self._workspace.menubar.addAction(self._workspace.menuWindow.menuAction())
1122            self._workspace.menubar.addAction(self._workspace.menuHelp.menuAction())
1123            self._workspace.actionReport.setEnabled(True)
1124
1125        elif isinstance(perspective, Perspectives.PERSPECTIVES["Invariant"]):
1126            self.checkAnalysisOption(self._workspace.actionInvariant)
1127        elif isinstance(perspective, Perspectives.PERSPECTIVES["Inversion"]):
1128            self.checkAnalysisOption(self._workspace.actionInversion)
1129        elif isinstance(perspective, Perspectives.PERSPECTIVES["Corfunc"]):
1130            self.checkAnalysisOption(self._workspace.actionCorfunc)
1131
1132    def saveCustomConfig(self):
1133        """
1134        Save the config file based on current session values
1135        """
1136        # Load the current file
1137        config_content = GuiUtils.custom_config
1138
1139        changed = self.customSavePaths(config_content)
1140        changed = changed or self.customSaveOpenCL(config_content)
1141
1142        if changed:
1143            self.writeCustomConfig(config_content)
1144
1145    def customSavePaths(self, config_content):
1146        """
1147        Update the config module with current session paths
1148        Returns True if update was done, False, otherwise
1149        """
1150        changed = False
1151        # Find load path
1152        open_path = GuiUtils.DEFAULT_OPEN_FOLDER
1153        defined_path = self.filesWidget.default_load_location
1154        if open_path != defined_path:
1155            # Replace the load path
1156            config_content.DEFAULT_OPEN_FOLDER = defined_path
1157            changed = True
1158        return changed
1159
1160    def customSaveOpenCL(self, config_content):
1161        """
1162        Update the config module with current session OpenCL choice
1163        Returns True if update was done, False, otherwise
1164        """
1165        changed = False
1166        # Find load path
1167        file_value = GuiUtils.SAS_OPENCL
1168        session_value = os.environ.get("SAS_OPENCL", "")
1169        if file_value != session_value:
1170            # Replace the load path
1171            config_content.SAS_OPENCL = session_value
1172            changed = True
1173        return changed
1174
1175    def writeCustomConfig(self, config):
1176        """
1177        Write custom configuration
1178        """
1179        from sas import make_custom_config_path
1180        path = make_custom_config_path()
1181        # Just clobber the file - we already have its content read in
1182        with open(path, 'w') as out_f:
1183            out_f.write("#Application appearance custom configuration\n")
1184            for key, item in config.__dict__.items():
1185                if key[:2] == "__":
1186                    continue
1187                if isinstance(item, str):
1188                    item = '"' + item + '"'
1189                out_f.write("%s = %s\n" % (key, str(item)))
1190        pass # debugger anchor
Note: See TracBrowser for help on using the repository browser.