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

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 5047898 was 12acdcc, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 6 years ago

Disabled the orientation viewer SASVIEW-1132

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