source: sasview/src/sas/qtgui/GuiManager.py @ 83d6249

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 83d6249 was 83d6249, checked in by Piotr Rozyczko <rozyczko@…>, 7 years ago

Perspectives are now switchable and can be added "dynamically"

  • Property mode set to 100644
File size: 23.4 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, mainWindow=None, reactor=None, parent=None):
49        """
50        Initialize the manager as a child of MainWindow.
51        """
52        self._workspace = mainWindow
53        self._parent = parent
54
55        # Reactor passed from above
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        self.addWidgets()
76
77        # Fork off logging messages to the Log Window
78        XStream.stdout().messageWritten.connect(self.listWidget.insertPlainText)
79        XStream.stderr().messageWritten.connect(self.listWidget.insertPlainText)
80
81        # Log the start of the session
82        logging.info(" --- SasView session started ---")
83        # Log the python version
84        logging.info("Python: %s" % sys.version)
85
86        # Set up the status bar
87        self.statusBarSetup()
88
89        # Show the Welcome panel
90        self.welcomePanel = WelcomePanel()
91        self._workspace.workspace.addWindow(self.welcomePanel)
92
93        # Current help file
94        self._helpView = QtWebKit.QWebView()
95        # Needs URL like path, so no path.join() here
96        self._helpLocation = self.HELP_DIRECTORY_LOCATION + "/index.html"
97
98        # Current tutorial location
99        self._tutorialLocation = os.path.abspath(os.path.join(self.HELP_DIRECTORY_LOCATION,
100                                              "_downloads",
101                                              "Tutorial.pdf"))
102        # Current displayed perspective
103        self._current_perspective = None
104
105        # Invoke the initial perspective
106        self.perspectiveChanged("Fitting")
107
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.close()
183        # Default perspective
184        self._current_perspective = Perspectives.PERSPECTIVES[str(perspective_name)](self)
185        self._workspace.workspace.addWindow(self._current_perspective)
186        self._current_perspective.show()
187
188    def updatePerspective(self, data):
189        """
190        """
191        assert isinstance(data, list)
192        if self._current_perspective is not None:
193            self._current_perspective.setData(data.values())
194        else:
195            msg = "No perspective is currently active."
196            logging.info(msg)
197
198
199    def communicator(self):
200        """ Accessor for the communicator """
201        return self.communicate
202
203    def reactor(self):
204        """ Accessor for the reactor """
205        return self._reactor
206
207    def setReactor(self, reactor):
208        """ Reactor setter """
209        self._reactor = reactor
210
211    def perspective(self):
212        """ Accessor for the perspective """
213        return self._current_perspective
214
215    def updateProgressBar(self, value):
216        """
217        Update progress bar with the required value (0-100)
218        """
219        assert -1 <= value <= 100
220        if value == -1:
221            self.progress.setVisible(False)
222            return
223        if not self.progress.isVisible():
224            self.progress.setTextVisible(True)
225            self.progress.setVisible(True)
226
227        self.progress.setValue(value)
228
229    def updateStatusBar(self, text):
230        """
231        """
232        #self._workspace.statusbar.showMessage(text)
233        self.statusLabel.setText(text)
234
235    def createGuiData(self, item, p_file=None):
236        """
237        Access the Data1D -> plottable Data1D conversion
238        """
239        return self._data_manager.create_gui_data(item, p_file)
240
241    def setData(self, data):
242        """
243        Sends data to current perspective
244        """
245        if self._current_perspective is not None:
246            self._current_perspective.setData(data.values())
247        else:
248            msg = "Guiframe does not have a current perspective"
249            logging.info(msg)
250
251    def quitApplication(self):
252        """
253        Close the reactor and exit nicely.
254        """
255        # Display confirmation messagebox
256        quit_msg = "Are you sure you want to exit the application?"
257        reply = QtGui.QMessageBox.question(
258            self._parent,
259            'Information',
260            quit_msg,
261            QtGui.QMessageBox.Yes,
262            QtGui.QMessageBox.No)
263
264        # Exit if yes
265        if reply == QtGui.QMessageBox.Yes:
266            reactor.callFromThread(reactor.stop)
267            return True
268
269        return False
270
271    def checkUpdate(self):
272        """
273        Check with the deployment server whether a new version
274        of the application is available.
275        A thread is started for the connecting with the server. The thread calls
276        a call-back method when the current version number has been obtained.
277        """
278        version_info = {"version": "0.0.0"}
279        c = Connection(LocalConfig.__update_URL__, LocalConfig.UPDATE_TIMEOUT)
280        response = c.connect()
281        if response is not None:
282            try:
283                content = response.read().strip()
284                logging.info("Connected to www.sasview.org. Latest version: %s"
285                             % (content))
286                version_info = json.loads(content)
287            except ValueError, ex:
288                logging.info("Failed to connect to www.sasview.org:", ex)
289        self.processVersion(version_info)
290
291    def processVersion(self, version_info):
292        """
293        Call-back method for the process of checking for updates.
294        This methods is called by a VersionThread object once the current
295        version number has been obtained. If the check is being done in the
296        background, the user will not be notified unless there's an update.
297
298        :param version: version string
299        """
300        try:
301            version = version_info["version"]
302            if version == "0.0.0":
303                msg = "Could not connect to the application server."
304                msg += " Please try again later."
305                #self.SetStatusText(msg)
306                self.communicate.statusBarUpdateSignal.emit(msg)
307
308            elif cmp(version, LocalConfig.__version__) > 0:
309                msg = "Version %s is available! " % str(version)
310                if "download_url" in version_info:
311                    webbrowser.open(version_info["download_url"])
312                else:
313                    webbrowser.open(LocalConfig.__download_page__)
314                self.communicate.statusBarUpdateSignal.emit(msg)
315            else:
316                msg = "You have the latest version"
317                msg += " of %s" % str(LocalConfig.__appname__)
318                self.communicate.statusBarUpdateSignal.emit(msg)
319        except:
320            msg = "guiframe: could not get latest application"
321            msg += " version number\n  %s" % sys.exc_value
322            logging.error(msg)
323            msg = "Could not connect to the application server."
324            msg += " Please try again later."
325            self.communicate.statusBarUpdateSignal.emit(msg)
326
327    def addCallbacks(self):
328        """
329        Method defining all signal connections for the gui manager
330        """
331        self.communicate = GuiUtils.Communicate()
332        self.communicate.fileDataReceivedSignal.connect(self.fileRead)
333        self.communicate.statusBarUpdateSignal.connect(self.updateStatusBar)
334        self.communicate.updatePerspectiveWithDataSignal.connect(self.updatePerspective)
335        self.communicate.progressBarUpdateSignal.connect(self.updateProgressBar)
336        self.communicate.perspectiveChangedSignal.connect(self.perspectiveChanged)
337
338    def addTriggers(self):
339        """
340        Trigger definitions for all menu/toolbar actions.
341        """
342        # File
343        self._workspace.actionLoadData.triggered.connect(self.actionLoadData)
344        self._workspace.actionLoad_Data_Folder.triggered.connect(self.actionLoad_Data_Folder)
345        self._workspace.actionOpen_Project.triggered.connect(self.actionOpen_Project)
346        self._workspace.actionOpen_Analysis.triggered.connect(self.actionOpen_Analysis)
347        self._workspace.actionSave.triggered.connect(self.actionSave)
348        self._workspace.actionSave_Analysis.triggered.connect(self.actionSave_Analysis)
349        self._workspace.actionQuit.triggered.connect(self.actionQuit)
350        # Edit
351        self._workspace.actionUndo.triggered.connect(self.actionUndo)
352        self._workspace.actionRedo.triggered.connect(self.actionRedo)
353        self._workspace.actionCopy.triggered.connect(self.actionCopy)
354        self._workspace.actionPaste.triggered.connect(self.actionPaste)
355        self._workspace.actionReport.triggered.connect(self.actionReport)
356        self._workspace.actionReset.triggered.connect(self.actionReset)
357        self._workspace.actionExcel.triggered.connect(self.actionExcel)
358        self._workspace.actionLatex.triggered.connect(self.actionLatex)
359
360        # View
361        self._workspace.actionShow_Grid_Window.triggered.connect(self.actionShow_Grid_Window)
362        self._workspace.actionHide_Toolbar.triggered.connect(self.actionHide_Toolbar)
363        self._workspace.actionStartup_Settings.triggered.connect(self.actionStartup_Settings)
364        self._workspace.actionCategry_Manager.triggered.connect(self.actionCategry_Manager)
365        # Tools
366        self._workspace.actionData_Operation.triggered.connect(self.actionData_Operation)
367        self._workspace.actionSLD_Calculator.triggered.connect(self.actionSLD_Calculator)
368        self._workspace.actionDensity_Volume_Calculator.triggered.connect(self.actionDensity_Volume_Calculator)
369        self._workspace.actionKeissig_Calculator.triggered.connect(self.actionKiessig_Calculator)
370        #self._workspace.actionKIESSING_Calculator.triggered.connect(self.actionKIESSING_Calculator)
371        self._workspace.actionSlit_Size_Calculator.triggered.connect(self.actionSlit_Size_Calculator)
372        self._workspace.actionSAS_Resolution_Estimator.triggered.connect(self.actionSAS_Resolution_Estimator)
373        self._workspace.actionGeneric_Scattering_Calculator.triggered.connect(self.actionGeneric_Scattering_Calculator)
374        self._workspace.actionPython_Shell_Editor.triggered.connect(self.actionPython_Shell_Editor)
375        self._workspace.actionImage_Viewer.triggered.connect(self.actionImage_Viewer)
376        # Fitting
377        self._workspace.actionNew_Fit_Page.triggered.connect(self.actionNew_Fit_Page)
378        self._workspace.actionConstrained_Fit.triggered.connect(self.actionConstrained_Fit)
379        self._workspace.actionCombine_Batch_Fit.triggered.connect(self.actionCombine_Batch_Fit)
380        self._workspace.actionFit_Options.triggered.connect(self.actionFit_Options)
381        self._workspace.actionFit_Results.triggered.connect(self.actionFit_Results)
382        self._workspace.actionChain_Fitting.triggered.connect(self.actionChain_Fitting)
383        self._workspace.actionEdit_Custom_Model.triggered.connect(self.actionEdit_Custom_Model)
384        # Window
385        self._workspace.actionCascade.triggered.connect(self.actionCascade)
386        self._workspace.actionTile.triggered.connect(self.actionTile)
387        self._workspace.actionArrange_Icons.triggered.connect(self.actionArrange_Icons)
388        self._workspace.actionNext.triggered.connect(self.actionNext)
389        self._workspace.actionPrevious.triggered.connect(self.actionPrevious)
390        # Analysis
391        self._workspace.actionFitting.triggered.connect(self.actionFitting)
392        self._workspace.actionInversion.triggered.connect(self.actionInversion)
393        self._workspace.actionInvariant.triggered.connect(self.actionInvariant)
394        # Help
395        self._workspace.actionDocumentation.triggered.connect(self.actionDocumentation)
396        self._workspace.actionTutorial.triggered.connect(self.actionTutorial)
397        self._workspace.actionAcknowledge.triggered.connect(self.actionAcknowledge)
398        self._workspace.actionAbout.triggered.connect(self.actionAbout)
399        self._workspace.actionCheck_for_update.triggered.connect(self.actionCheck_for_update)
400
401    #============ FILE =================
402    def actionLoadData(self):
403        """
404        Menu File/Load Data File(s)
405        """
406        self.filesWidget.loadFile()
407
408    def actionLoad_Data_Folder(self):
409        """
410        Menu File/Load Data Folder
411        """
412        self.filesWidget.loadFolder()
413
414    def actionOpen_Project(self):
415        """
416        Menu Open Project
417        """
418        self.filesWidget.loadProject()
419
420    def actionOpen_Analysis(self):
421        """
422        """
423        print("actionOpen_Analysis TRIGGERED")
424        pass
425
426    def actionSave(self):
427        """
428        Menu Save Project
429        """
430        self.filesWidget.saveProject()
431
432    def actionSave_Analysis(self):
433        """
434        """
435        print("actionSave_Analysis TRIGGERED")
436
437        pass
438
439    def actionQuit(self):
440        """
441        Close the reactor, exit the application.
442        """
443        self.quitApplication()
444
445    #============ EDIT =================
446    def actionUndo(self):
447        """
448        """
449        print("actionUndo TRIGGERED")
450        pass
451
452    def actionRedo(self):
453        """
454        """
455        print("actionRedo TRIGGERED")
456        pass
457
458    def actionCopy(self):
459        """
460        """
461        print("actionCopy TRIGGERED")
462        pass
463
464    def actionPaste(self):
465        """
466        """
467        print("actionPaste TRIGGERED")
468        pass
469
470    def actionReport(self):
471        """
472        """
473        print("actionReport TRIGGERED")
474        pass
475
476    def actionReset(self):
477        """
478        """
479        logging.warning(" *** actionOpen_Analysis logging *******")
480        print("actionReset print TRIGGERED")
481        sys.stderr.write("STDERR - TRIGGERED")
482        pass
483
484    def actionExcel(self):
485        """
486        """
487        print("actionExcel TRIGGERED")
488        pass
489
490    def actionLatex(self):
491        """
492        """
493        print("actionLatex TRIGGERED")
494        pass
495
496    #============ VIEW =================
497    def actionShow_Grid_Window(self):
498        """
499        """
500        print("actionShow_Grid_Window TRIGGERED")
501        pass
502
503    def actionHide_Toolbar(self):
504        """
505        Toggle toolbar vsibility
506        """
507        if self._workspace.toolBar.isVisible():
508            self._workspace.actionHide_Toolbar.setText("Show Toolbar")
509            self._workspace.toolBar.setVisible(False)
510        else:
511            self._workspace.actionHide_Toolbar.setText("Hide Toolbar")
512            self._workspace.toolBar.setVisible(True)
513        pass
514
515    def actionStartup_Settings(self):
516        """
517        """
518        print("actionStartup_Settings TRIGGERED")
519        pass
520
521    def actionCategry_Manager(self):
522        """
523        """
524        print("actionCategry_Manager TRIGGERED")
525        pass
526
527    #============ TOOLS =================
528    def actionData_Operation(self):
529        """
530        """
531        print("actionData_Operation TRIGGERED")
532        pass
533
534    def actionSLD_Calculator(self):
535        """
536        """
537        self.SLDCalculator.show()
538
539    def actionDensity_Volume_Calculator(self):
540        """
541        """
542        self.DVCalculator.show()
543
544    def actionKiessig_Calculator(self):
545        """
546        """
547        #self.DVCalculator.show()
548        self.KIESSIGCalculator.show()
549
550    def actionSlit_Size_Calculator(self):
551        """
552        """
553        self.SlitSizeCalculator.show()
554
555    def actionSAS_Resolution_Estimator(self):
556        """
557        """
558        print("actionSAS_Resolution_Estimator TRIGGERED")
559        pass
560
561    def actionGeneric_Scattering_Calculator(self):
562        """
563        """
564        print("actionGeneric_Scattering_Calculator TRIGGERED")
565        pass
566
567    def actionPython_Shell_Editor(self):
568        """
569        Display the Jupyter console as a docked widget.
570        """
571        terminal = IPythonWidget()
572
573        # Add the console window as another docked widget
574        self.ipDockWidget = QtGui.QDockWidget("IPython", self._workspace)
575        self.ipDockWidget.setObjectName("IPythonDockWidget")
576        self.ipDockWidget.setWidget(terminal)
577        self._workspace.addDockWidget(QtCore.Qt.RightDockWidgetArea,
578                                      self.ipDockWidget)
579
580    def actionImage_Viewer(self):
581        """
582        """
583        print("actionImage_Viewer TRIGGERED")
584        pass
585
586    #============ FITTING =================
587    def actionNew_Fit_Page(self):
588        """
589        """
590        print("actionNew_Fit_Page TRIGGERED")
591        pass
592
593    def actionConstrained_Fit(self):
594        """
595        """
596        print("actionConstrained_Fit TRIGGERED")
597        pass
598
599    def actionCombine_Batch_Fit(self):
600        """
601        """
602        print("actionCombine_Batch_Fit TRIGGERED")
603        pass
604
605    def actionFit_Options(self):
606        """
607        """
608        print("actionFit_Options TRIGGERED")
609        pass
610
611    def actionFit_Results(self):
612        """
613        """
614        print("actionFit_Results TRIGGERED")
615        pass
616
617    def actionChain_Fitting(self):
618        """
619        """
620        print("actionChain_Fitting TRIGGERED")
621        pass
622
623    def actionEdit_Custom_Model(self):
624        """
625        """
626        print("actionEdit_Custom_Model TRIGGERED")
627        pass
628
629    #============ ANALYSIS =================
630    def actionFitting(self):
631        """
632        """
633        print("actionFitting TRIGGERED")
634        pass
635
636    def actionInversion(self):
637        """
638        """
639        print("actionInversion TRIGGERED")
640        pass
641
642    def actionInvariant(self):
643        """
644        """
645        print("actionInvariant TRIGGERED")
646        pass
647
648    #============ WINDOW =================
649    def actionCascade(self):
650        """
651        Arranges all the child windows in a cascade pattern.
652        """
653        self._workspace.workspace.cascade()
654
655    def actionTile(self):
656        """
657        Tile workspace windows
658        """
659        self._workspace.workspace.tile()
660
661    def actionArrange_Icons(self):
662        """
663        Arranges all iconified windows at the bottom of the workspace
664        """
665        self._workspace.workspace.arrangeIcons()
666
667    def actionNext(self):
668        """
669        Gives the input focus to the next window in the list of child windows.
670        """
671        self._workspace.workspace.activateNextWindow()
672
673    def actionPrevious(self):
674        """
675        Gives the input focus to the previous window in the list of child windows.
676        """
677        self._workspace.workspace.activatePreviousWindow()
678
679    #============ HELP =================
680    def actionDocumentation(self):
681        """
682        Display the documentation
683
684        TODO: use QNetworkAccessManager to assure _helpLocation is valid
685        """
686        self._helpView.load(QtCore.QUrl(self._helpLocation))
687        self._helpView.show()
688
689    def actionTutorial(self):
690        """
691        Open the tutorial PDF file with default PDF renderer
692        """
693        # Not terribly safe here. Shell injection warning.
694        # isfile() helps but this probably needs a better solution.
695        if os.path.isfile(self._tutorialLocation):
696            result = subprocess.Popen([self._tutorialLocation], shell=True)
697
698    def actionAcknowledge(self):
699        """
700        Open the Acknowledgements widget
701        """
702        self.ackWidget.show()
703
704    def actionAbout(self):
705        """
706        Open the About box
707        """
708        # Update the about box with current version and stuff
709
710        # TODO: proper sizing
711        self.aboutWidget.show()
712
713    def actionCheck_for_update(self):
714        """
715        Menu Help/Check for Update
716        """
717        self.checkUpdate()
718
719        pass
720
Note: See TracBrowser for help on using the repository browser.