source: sasview/src/sas/qtgui/GuiManager.py @ 116260a

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 116260a was 6fd4e36, checked in by Piotr Rozyczko <rozyczko@…>, 8 years ago

Chi2 display + minor refactoring

  • Property mode set to 100644
File size: 24.0 KB
Line 
1import sys
2import os
3import subprocess
4import logging
5import json
6import webbrowser
7
8from PyQt4 import QtCore
9from PyQt4 import QtGui
10from PyQt4 import QtWebKit
11
12from twisted.internet import reactor
13# General SAS imports
14
15from sas.sasgui.guiframe.data_manager import DataManager
16from sas.sasgui.guiframe.proxy import Connection
17from sas.qtgui.SasviewLogger import XStream
18import sas.qtgui.LocalConfig as LocalConfig
19import sas.qtgui.GuiUtils as GuiUtils
20from sas.qtgui.UI.AcknowledgementsUI import Ui_Acknowledgements
21from sas.qtgui.AboutBox import AboutBox
22from sas.qtgui.IPythonWidget import IPythonWidget
23from sas.qtgui.WelcomePanel import WelcomePanel
24
25from sas.qtgui.SldPanel import SldPanel
26from sas.qtgui.DensityPanel import DensityPanel
27from sas.qtgui.KiessigPanel import KiessigPanel
28from sas.qtgui.SlitSizeCalculator import SlitSizeCalculator
29
30# Perspectives
31import Perspectives
32from sas.qtgui.Perspectives.Invariant.InvariantPerspective import InvariantWindow
33from sas.qtgui.Perspectives.Fitting.FittingPerspective import FittingWindow
34from sas.qtgui.DataExplorer import DataExplorerWindow
35
36class Acknowledgements(QtGui.QDialog, Ui_Acknowledgements):
37    def __init__(self, parent=None):
38        QtGui.QDialog.__init__(self, parent)
39        self.setupUi(self)
40
41class GuiManager(object):
42    """
43    Main SasView window functionality
44    """
45    ## TODO: CHANGE FOR SHIPPED PATH IN RELEASE
46    HELP_DIRECTORY_LOCATION = "docs/sphinx-docs/build/html"
47
48    def __init__(self, parent=None):
49        """
50        Initialize the manager as a child of MainWindow.
51        """
52        self._workspace = parent
53        self._parent = parent
54
55        # Reactor - singleton
56        self.setReactor(reactor)
57
58        # Add signal callbacks
59        self.addCallbacks()
60
61        # Create the data manager
62        # TODO: pull out all required methods from DataManager and reimplement
63        self._data_manager = DataManager()
64
65        # Create action triggers
66        self.addTriggers()
67
68        # Populate menus with dynamic data
69        #
70        # Analysis/Perspectives - potentially
71        # Window/current windows
72        #
73        # Widgets
74        #
75        # Current displayed perspective
76        self._current_perspective = None
77
78        # Invoke the initial perspective
79        self.perspectiveChanged("Fitting")
80
81        self.addWidgets()
82
83        # Fork off logging messages to the Log Window
84        XStream.stdout().messageWritten.connect(self.listWidget.insertPlainText)
85        XStream.stderr().messageWritten.connect(self.listWidget.insertPlainText)
86
87        # Log the start of the session
88        logging.info(" --- SasView session started ---")
89        # Log the python version
90        logging.info("Python: %s" % sys.version)
91
92        # Set up the status bar
93        self.statusBarSetup()
94
95        # Show the Welcome panel
96        self.welcomePanel = WelcomePanel()
97        self._workspace.workspace.addWindow(self.welcomePanel)
98
99        # Current help file
100        self._helpView = QtWebKit.QWebView()
101        # Needs URL like path, so no path.join() here
102        self._helpLocation = self.HELP_DIRECTORY_LOCATION + "/index.html"
103
104        # Current tutorial location
105        self._tutorialLocation = os.path.abspath(os.path.join(self.HELP_DIRECTORY_LOCATION,
106                                              "_downloads",
107                                              "Tutorial.pdf"))
108    def addWidgets(self):
109        """
110        Populate the main window with widgets
111
112        TODO: overwrite close() on Log and DR widgets so they can be hidden/shown
113        on request
114        """
115        # Add FileDialog widget as docked
116        self.filesWidget = DataExplorerWindow(self._parent, self, manager=self._data_manager)
117
118        self.dockedFilesWidget = QtGui.QDockWidget("Data Explorer", self._workspace)
119        self.dockedFilesWidget.setWidget(self.filesWidget)
120
121        # Disable maximize/minimize and close buttons
122        self.dockedFilesWidget.setFeatures(QtGui.QDockWidget.NoDockWidgetFeatures)
123        self._workspace.addDockWidget(QtCore.Qt.LeftDockWidgetArea,
124                                      self.dockedFilesWidget)
125
126        # Add the console window as another docked widget
127        self.logDockWidget = QtGui.QDockWidget("Log Explorer", self._workspace)
128        self.logDockWidget.setObjectName("LogDockWidget")
129        self.listWidget = QtGui.QTextBrowser()
130        self.logDockWidget.setWidget(self.listWidget)
131        self._workspace.addDockWidget(QtCore.Qt.BottomDockWidgetArea,
132                                      self.logDockWidget)
133
134        # Add other, minor widgets
135        self.ackWidget = Acknowledgements()
136        self.aboutWidget = AboutBox()
137
138        # Add calculators - floating for usability
139        self.SLDCalculator = SldPanel(self)
140        self.DVCalculator = DensityPanel(self)
141        #self.KIESSIGCalculator = DensityPanel(self)#KiessigPanel(self)
142        self.KIESSIGCalculator = KiessigPanel(self)
143        self.SlitSizeCalculator = SlitSizeCalculator(self)
144
145    def statusBarSetup(self):
146        """
147        Define the status bar.
148        | <message label> .... | Progress Bar |
149
150        Progress bar invisible until explicitly shown
151        """
152        self.progress = QtGui.QProgressBar()
153        self._workspace.statusbar.setSizeGripEnabled(False)
154
155        self.statusLabel = QtGui.QLabel()
156        self.statusLabel.setText("Welcome to SasView")
157        self._workspace.statusbar.addPermanentWidget(self.statusLabel, 1)
158        self._workspace.statusbar.addPermanentWidget(self.progress, stretch=0)
159        self.progress.setRange(0, 100)
160        self.progress.setValue(0)
161        self.progress.setTextVisible(True)
162        self.progress.setVisible(False)
163
164    def fileRead(self, data):
165        """
166        Callback for fileDataReceivedSignal
167        """
168        pass
169
170    def workspace(self):
171        """
172        Accessor for the main window workspace
173        """
174        return self._workspace.workspace
175
176    def perspectiveChanged(self, perspective_name):
177        """
178        Respond to change of the perspective signal
179        """
180        # Close the previous perspective
181        if self._current_perspective:
182            self._current_perspective.setClosable()
183            self._current_perspective.close()
184        # Default perspective
185        self._current_perspective = Perspectives.PERSPECTIVES[str(perspective_name)](parent=self)
186        self._workspace.workspace.addWindow(self._current_perspective)
187        self._current_perspective.show()
188
189    def updatePerspective(self, data):
190        """
191        """
192        assert isinstance(data, list)
193        if self._current_perspective is not None:
194            self._current_perspective.setData(data.values())
195        else:
196            msg = "No perspective is currently active."
197            logging.info(msg)
198
199
200    def communicator(self):
201        """ Accessor for the communicator """
202        return self.communicate
203
204    def reactor(self):
205        """ Accessor for the reactor """
206        return self._reactor
207
208    def setReactor(self, reactor):
209        """ Reactor setter """
210        self._reactor = reactor
211
212    def perspective(self):
213        """ Accessor for the perspective """
214        return self._current_perspective
215
216    def updateProgressBar(self, value):
217        """
218        Update progress bar with the required value (0-100)
219        """
220        assert -1 <= value <= 100
221        if value == -1:
222            self.progress.setVisible(False)
223            return
224        if not self.progress.isVisible():
225            self.progress.setTextVisible(True)
226            self.progress.setVisible(True)
227
228        self.progress.setValue(value)
229
230    def updateStatusBar(self, text):
231        """
232        """
233        #self._workspace.statusbar.showMessage(text)
234        self.statusLabel.setText(text)
235
236    def createGuiData(self, item, p_file=None):
237        """
238        Access the Data1D -> plottable Data1D conversion
239        """
240        return self._data_manager.create_gui_data(item, p_file)
241
242    def setData(self, data):
243        """
244        Sends data to current perspective
245        """
246        if self._current_perspective is not None:
247            self._current_perspective.setData(data.values())
248        else:
249            msg = "Guiframe does not have a current perspective"
250            logging.info(msg)
251
252    def quitApplication(self):
253        """
254        Close the reactor and exit nicely.
255        """
256        # Display confirmation messagebox
257        quit_msg = "Are you sure you want to exit the application?"
258        reply = QtGui.QMessageBox.question(
259            self._parent,
260            'Information',
261            quit_msg,
262            QtGui.QMessageBox.Yes,
263            QtGui.QMessageBox.No)
264
265        # Exit if yes
266        if reply == QtGui.QMessageBox.Yes:
267            reactor.callFromThread(reactor.stop)
268            return True
269
270        return False
271
272    def checkUpdate(self):
273        """
274        Check with the deployment server whether a new version
275        of the application is available.
276        A thread is started for the connecting with the server. The thread calls
277        a call-back method when the current version number has been obtained.
278        """
279        version_info = {"version": "0.0.0"}
280        c = Connection(LocalConfig.__update_URL__, LocalConfig.UPDATE_TIMEOUT)
281        response = c.connect()
282        if response is not None:
283            try:
284                content = response.read().strip()
285                logging.info("Connected to www.sasview.org. Latest version: %s"
286                             % (content))
287                version_info = json.loads(content)
288            except ValueError, ex:
289                logging.info("Failed to connect to www.sasview.org:", ex)
290        self.processVersion(version_info)
291
292    def processVersion(self, version_info):
293        """
294        Call-back method for the process of checking for updates.
295        This methods is called by a VersionThread object once the current
296        version number has been obtained. If the check is being done in the
297        background, the user will not be notified unless there's an update.
298
299        :param version: version string
300        """
301        try:
302            version = version_info["version"]
303            if version == "0.0.0":
304                msg = "Could not connect to the application server."
305                msg += " Please try again later."
306                #self.SetStatusText(msg)
307                self.communicate.statusBarUpdateSignal.emit(msg)
308
309            elif cmp(version, LocalConfig.__version__) > 0:
310                msg = "Version %s is available! " % str(version)
311                if "download_url" in version_info:
312                    webbrowser.open(version_info["download_url"])
313                else:
314                    webbrowser.open(LocalConfig.__download_page__)
315                self.communicate.statusBarUpdateSignal.emit(msg)
316            else:
317                msg = "You have the latest version"
318                msg += " of %s" % str(LocalConfig.__appname__)
319                self.communicate.statusBarUpdateSignal.emit(msg)
320        except:
321            msg = "guiframe: could not get latest application"
322            msg += " version number\n  %s" % sys.exc_value
323            logging.error(msg)
324            msg = "Could not connect to the application server."
325            msg += " Please try again later."
326            self.communicate.statusBarUpdateSignal.emit(msg)
327
328    def addCallbacks(self):
329        """
330        Method defining all signal connections for the gui manager
331        """
332        self.communicate = GuiUtils.Communicate()
333        self.communicate.fileDataReceivedSignal.connect(self.fileRead)
334        self.communicate.statusBarUpdateSignal.connect(self.updateStatusBar)
335        self.communicate.updatePerspectiveWithDataSignal.connect(self.updatePerspective)
336        self.communicate.progressBarUpdateSignal.connect(self.updateProgressBar)
337        self.communicate.perspectiveChangedSignal.connect(self.perspectiveChanged)
338        self.communicate.updateTheoryFromPerspectiveSignal.connect(self.updateTheoryFromPerspective)
339
340    def addTriggers(self):
341        """
342        Trigger definitions for all menu/toolbar actions.
343        """
344        # File
345        self._workspace.actionLoadData.triggered.connect(self.actionLoadData)
346        self._workspace.actionLoad_Data_Folder.triggered.connect(self.actionLoad_Data_Folder)
347        self._workspace.actionOpen_Project.triggered.connect(self.actionOpen_Project)
348        self._workspace.actionOpen_Analysis.triggered.connect(self.actionOpen_Analysis)
349        self._workspace.actionSave.triggered.connect(self.actionSave)
350        self._workspace.actionSave_Analysis.triggered.connect(self.actionSave_Analysis)
351        self._workspace.actionQuit.triggered.connect(self.actionQuit)
352        # Edit
353        self._workspace.actionUndo.triggered.connect(self.actionUndo)
354        self._workspace.actionRedo.triggered.connect(self.actionRedo)
355        self._workspace.actionCopy.triggered.connect(self.actionCopy)
356        self._workspace.actionPaste.triggered.connect(self.actionPaste)
357        self._workspace.actionReport.triggered.connect(self.actionReport)
358        self._workspace.actionReset.triggered.connect(self.actionReset)
359        self._workspace.actionExcel.triggered.connect(self.actionExcel)
360        self._workspace.actionLatex.triggered.connect(self.actionLatex)
361
362        # View
363        self._workspace.actionShow_Grid_Window.triggered.connect(self.actionShow_Grid_Window)
364        self._workspace.actionHide_Toolbar.triggered.connect(self.actionHide_Toolbar)
365        self._workspace.actionStartup_Settings.triggered.connect(self.actionStartup_Settings)
366        self._workspace.actionCategry_Manager.triggered.connect(self.actionCategry_Manager)
367        # Tools
368        self._workspace.actionData_Operation.triggered.connect(self.actionData_Operation)
369        self._workspace.actionSLD_Calculator.triggered.connect(self.actionSLD_Calculator)
370        self._workspace.actionDensity_Volume_Calculator.triggered.connect(self.actionDensity_Volume_Calculator)
371        self._workspace.actionKeissig_Calculator.triggered.connect(self.actionKiessig_Calculator)
372        #self._workspace.actionKIESSING_Calculator.triggered.connect(self.actionKIESSING_Calculator)
373        self._workspace.actionSlit_Size_Calculator.triggered.connect(self.actionSlit_Size_Calculator)
374        self._workspace.actionSAS_Resolution_Estimator.triggered.connect(self.actionSAS_Resolution_Estimator)
375        self._workspace.actionGeneric_Scattering_Calculator.triggered.connect(self.actionGeneric_Scattering_Calculator)
376        self._workspace.actionPython_Shell_Editor.triggered.connect(self.actionPython_Shell_Editor)
377        self._workspace.actionImage_Viewer.triggered.connect(self.actionImage_Viewer)
378        # Fitting
379        self._workspace.actionNew_Fit_Page.triggered.connect(self.actionNew_Fit_Page)
380        self._workspace.actionConstrained_Fit.triggered.connect(self.actionConstrained_Fit)
381        self._workspace.actionCombine_Batch_Fit.triggered.connect(self.actionCombine_Batch_Fit)
382        self._workspace.actionFit_Options.triggered.connect(self.actionFit_Options)
383        self._workspace.actionFit_Results.triggered.connect(self.actionFit_Results)
384        self._workspace.actionChain_Fitting.triggered.connect(self.actionChain_Fitting)
385        self._workspace.actionEdit_Custom_Model.triggered.connect(self.actionEdit_Custom_Model)
386        # Window
387        self._workspace.actionCascade.triggered.connect(self.actionCascade)
388        self._workspace.actionTile.triggered.connect(self.actionTile)
389        self._workspace.actionArrange_Icons.triggered.connect(self.actionArrange_Icons)
390        self._workspace.actionNext.triggered.connect(self.actionNext)
391        self._workspace.actionPrevious.triggered.connect(self.actionPrevious)
392        # Analysis
393        self._workspace.actionFitting.triggered.connect(self.actionFitting)
394        self._workspace.actionInversion.triggered.connect(self.actionInversion)
395        self._workspace.actionInvariant.triggered.connect(self.actionInvariant)
396        # Help
397        self._workspace.actionDocumentation.triggered.connect(self.actionDocumentation)
398        self._workspace.actionTutorial.triggered.connect(self.actionTutorial)
399        self._workspace.actionAcknowledge.triggered.connect(self.actionAcknowledge)
400        self._workspace.actionAbout.triggered.connect(self.actionAbout)
401        self._workspace.actionCheck_for_update.triggered.connect(self.actionCheck_for_update)
402
403    #============ FILE =================
404    def actionLoadData(self):
405        """
406        Menu File/Load Data File(s)
407        """
408        self.filesWidget.loadFile()
409
410    def actionLoad_Data_Folder(self):
411        """
412        Menu File/Load Data Folder
413        """
414        self.filesWidget.loadFolder()
415
416    def actionOpen_Project(self):
417        """
418        Menu Open Project
419        """
420        self.filesWidget.loadProject()
421
422    def actionOpen_Analysis(self):
423        """
424        """
425        print("actionOpen_Analysis TRIGGERED")
426        pass
427
428    def actionSave(self):
429        """
430        Menu Save Project
431        """
432        self.filesWidget.saveProject()
433
434    def actionSave_Analysis(self):
435        """
436        """
437        print("actionSave_Analysis TRIGGERED")
438
439        pass
440
441    def actionQuit(self):
442        """
443        Close the reactor, exit the application.
444        """
445        self.quitApplication()
446
447    #============ EDIT =================
448    def actionUndo(self):
449        """
450        """
451        print("actionUndo TRIGGERED")
452        pass
453
454    def actionRedo(self):
455        """
456        """
457        print("actionRedo TRIGGERED")
458        pass
459
460    def actionCopy(self):
461        """
462        """
463        print("actionCopy TRIGGERED")
464        pass
465
466    def actionPaste(self):
467        """
468        """
469        print("actionPaste TRIGGERED")
470        pass
471
472    def actionReport(self):
473        """
474        """
475        print("actionReport TRIGGERED")
476        pass
477
478    def actionReset(self):
479        """
480        """
481        logging.warning(" *** actionOpen_Analysis logging *******")
482        print("actionReset print TRIGGERED")
483        sys.stderr.write("STDERR - TRIGGERED")
484        pass
485
486    def actionExcel(self):
487        """
488        """
489        print("actionExcel TRIGGERED")
490        pass
491
492    def actionLatex(self):
493        """
494        """
495        print("actionLatex TRIGGERED")
496        pass
497
498    #============ VIEW =================
499    def actionShow_Grid_Window(self):
500        """
501        """
502        print("actionShow_Grid_Window TRIGGERED")
503        pass
504
505    def actionHide_Toolbar(self):
506        """
507        Toggle toolbar vsibility
508        """
509        if self._workspace.toolBar.isVisible():
510            self._workspace.actionHide_Toolbar.setText("Show Toolbar")
511            self._workspace.toolBar.setVisible(False)
512        else:
513            self._workspace.actionHide_Toolbar.setText("Hide Toolbar")
514            self._workspace.toolBar.setVisible(True)
515        pass
516
517    def actionStartup_Settings(self):
518        """
519        """
520        print("actionStartup_Settings TRIGGERED")
521        pass
522
523    def actionCategry_Manager(self):
524        """
525        """
526        print("actionCategry_Manager TRIGGERED")
527        pass
528
529    #============ TOOLS =================
530    def actionData_Operation(self):
531        """
532        """
533        print("actionData_Operation TRIGGERED")
534        pass
535
536    def actionSLD_Calculator(self):
537        """
538        """
539        self.SLDCalculator.show()
540
541    def actionDensity_Volume_Calculator(self):
542        """
543        """
544        self.DVCalculator.show()
545
546    def actionKiessig_Calculator(self):
547        """
548        """
549        #self.DVCalculator.show()
550        self.KIESSIGCalculator.show()
551
552    def actionSlit_Size_Calculator(self):
553        """
554        """
555        self.SlitSizeCalculator.show()
556
557    def actionSAS_Resolution_Estimator(self):
558        """
559        """
560        print("actionSAS_Resolution_Estimator TRIGGERED")
561        pass
562
563    def actionGeneric_Scattering_Calculator(self):
564        """
565        """
566        print("actionGeneric_Scattering_Calculator TRIGGERED")
567        pass
568
569    def actionPython_Shell_Editor(self):
570        """
571        Display the Jupyter console as a docked widget.
572        """
573        terminal = IPythonWidget()
574
575        # Add the console window as another docked widget
576        self.ipDockWidget = QtGui.QDockWidget("IPython", self._workspace)
577        self.ipDockWidget.setObjectName("IPythonDockWidget")
578        self.ipDockWidget.setWidget(terminal)
579        self._workspace.addDockWidget(QtCore.Qt.RightDockWidgetArea,
580                                      self.ipDockWidget)
581
582    def actionImage_Viewer(self):
583        """
584        """
585        print("actionImage_Viewer TRIGGERED")
586        pass
587
588    #============ FITTING =================
589    def actionNew_Fit_Page(self):
590        """
591        Add a new, empty Fit page in the fitting perspective.
592        """
593        # Make sure the perspective is correct
594        per = self.perspective()
595        if not isinstance(per, FittingWindow):
596            return
597        per.addFit(None)
598
599    def actionConstrained_Fit(self):
600        """
601        """
602        print("actionConstrained_Fit TRIGGERED")
603        pass
604
605    def actionCombine_Batch_Fit(self):
606        """
607        """
608        print("actionCombine_Batch_Fit TRIGGERED")
609        pass
610
611    def actionFit_Options(self):
612        """
613        """
614        print("actionFit_Options TRIGGERED")
615        pass
616
617    def actionFit_Results(self):
618        """
619        """
620        print("actionFit_Results TRIGGERED")
621        pass
622
623    def actionChain_Fitting(self):
624        """
625        """
626        print("actionChain_Fitting TRIGGERED")
627        pass
628
629    def actionEdit_Custom_Model(self):
630        """
631        """
632        print("actionEdit_Custom_Model TRIGGERED")
633        pass
634
635    #============ ANALYSIS =================
636    def actionFitting(self):
637        """
638        """
639        print("actionFitting TRIGGERED")
640        pass
641
642    def actionInversion(self):
643        """
644        """
645        print("actionInversion TRIGGERED")
646        pass
647
648    def actionInvariant(self):
649        """
650        """
651        print("actionInvariant TRIGGERED")
652        pass
653
654    #============ WINDOW =================
655    def actionCascade(self):
656        """
657        Arranges all the child windows in a cascade pattern.
658        """
659        self._workspace.workspace.cascade()
660
661    def actionTile(self):
662        """
663        Tile workspace windows
664        """
665        self._workspace.workspace.tile()
666
667    def actionArrange_Icons(self):
668        """
669        Arranges all iconified windows at the bottom of the workspace
670        """
671        self._workspace.workspace.arrangeIcons()
672
673    def actionNext(self):
674        """
675        Gives the input focus to the next window in the list of child windows.
676        """
677        self._workspace.workspace.activateNextWindow()
678
679    def actionPrevious(self):
680        """
681        Gives the input focus to the previous window in the list of child windows.
682        """
683        self._workspace.workspace.activatePreviousWindow()
684
685    #============ HELP =================
686    def actionDocumentation(self):
687        """
688        Display the documentation
689
690        TODO: use QNetworkAccessManager to assure _helpLocation is valid
691        """
692        self._helpView.load(QtCore.QUrl(self._helpLocation))
693        self._helpView.show()
694
695    def actionTutorial(self):
696        """
697        Open the tutorial PDF file with default PDF renderer
698        """
699        # Not terribly safe here. Shell injection warning.
700        # isfile() helps but this probably needs a better solution.
701        if os.path.isfile(self._tutorialLocation):
702            result = subprocess.Popen([self._tutorialLocation], shell=True)
703
704    def actionAcknowledge(self):
705        """
706        Open the Acknowledgements widget
707        """
708        self.ackWidget.show()
709
710    def actionAbout(self):
711        """
712        Open the About box
713        """
714        # Update the about box with current version and stuff
715
716        # TODO: proper sizing
717        self.aboutWidget.show()
718
719    def actionCheck_for_update(self):
720        """
721        Menu Help/Check for Update
722        """
723        self.checkUpdate()
724
725    def updateTheoryFromPerspective(self, index):
726        """
727        Catch the theory update signal from a perspective
728        Send the request to the DataExplorer for updating the theory model.
729        """
730        self.filesWidget.updateTheoryFromPerspective(index)
731
732
733
Note: See TracBrowser for help on using the repository browser.