source: sasview/src/sas/qtgui/DataExplorer.py @ 49e124c

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

Initial functionality of Plot2D

  • Property mode set to 100644
File size: 30.7 KB
Line 
1# global
2import sys
3import os
4import time
5import logging
6
7from PyQt4 import QtCore
8from PyQt4 import QtGui
9from PyQt4 import QtWebKit
10from PyQt4.Qt import QMutex
11
12from twisted.internet import threads
13
14# SAS
15from sas.sascalc.dataloader.loader import Loader
16from sas.sasgui.guiframe.data_manager import DataManager
17from sas.sasgui.guiframe.dataFitting import Data1D
18from sas.sasgui.guiframe.dataFitting import Data2D
19
20import GuiUtils
21import PlotHelper
22from Plotter import Plotter
23from Plotter2D import Plotter2D
24from DroppableDataLoadWidget import DroppableDataLoadWidget
25
26# This is how to get data1/2D from the model item
27# data = [selected_items[0].child(0).data().toPyObject()]
28
29class DataExplorerWindow(DroppableDataLoadWidget):
30    # The controller which is responsible for managing signal slots connections
31    # for the gui and providing an interface to the data model.
32
33    def __init__(self, parent=None, guimanager=None, manager=None):
34        super(DataExplorerWindow, self).__init__(parent, guimanager)
35
36        # Main model for keeping loaded data
37        self.model = QtGui.QStandardItemModel(self)
38
39        # Secondary model for keeping frozen data sets
40        self.theory_model = QtGui.QStandardItemModel(self)
41
42        # GuiManager is the actual parent, but we needed to also pass the QMainWindow
43        # in order to set the widget parentage properly.
44        self.parent = guimanager
45        self.loader = Loader()
46        self.manager = manager if manager is not None else DataManager()
47        self.txt_widget = QtGui.QTextEdit(None)
48        # self.txt_widget = GuiUtils.DisplayWindow()
49
50
51        # Be careful with twisted threads.
52        self.mutex = QMutex()
53
54        # Active plots
55        self.active_plots = []
56
57        # Connect the buttons
58        self.cmdLoad.clicked.connect(self.loadFile)
59        self.cmdDeleteData.clicked.connect(self.deleteFile)
60        self.cmdDeleteTheory.clicked.connect(self.deleteTheory)
61        self.cmdFreeze.clicked.connect(self.freezeTheory)
62        self.cmdSendTo.clicked.connect(self.sendData)
63        self.cmdNew.clicked.connect(self.newPlot)
64        self.cmdAppend.clicked.connect(self.appendPlot)
65        self.cmdHelp.clicked.connect(self.displayHelp)
66        self.cmdHelp_2.clicked.connect(self.displayHelp)
67
68        # Display HTML content
69        self._helpView = QtWebKit.QWebView()
70
71        # Custom context menu
72        self.treeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
73        self.treeView.customContextMenuRequested.connect(self.onCustomContextMenu)
74        self.contextMenu()
75
76        # Connect the comboboxes
77        self.cbSelect.currentIndexChanged.connect(self.selectData)
78
79        #self.closeEvent.connect(self.closeEvent)
80        # self.aboutToQuit.connect(self.closeEvent)
81        self.communicator = self.parent.communicator()
82        self.communicator.fileReadSignal.connect(self.loadFromURL)
83        self.communicator.activeGraphsSignal.connect(self.updateGraphCombo)
84        self.cbgraph.editTextChanged.connect(self.enableGraphCombo)
85        self.cbgraph.currentIndexChanged.connect(self.enableGraphCombo)
86
87        # Proxy model for showing a subset of Data1D/Data2D content
88        self.data_proxy = QtGui.QSortFilterProxyModel(self)
89        self.data_proxy.setSourceModel(self.model)
90
91        # Don't show "empty" rows with data objects
92        self.data_proxy.setFilterRegExp(r"[^()]")
93
94        # The Data viewer is QTreeView showing the proxy model
95        self.treeView.setModel(self.data_proxy)
96
97        # Proxy model for showing a subset of Theory content
98        self.theory_proxy = QtGui.QSortFilterProxyModel(self)
99        self.theory_proxy.setSourceModel(self.theory_model)
100
101        # Don't show "empty" rows with data objects
102        self.theory_proxy.setFilterRegExp(r"[^()]")
103
104        # Theory model view
105        self.freezeView.setModel(self.theory_proxy)
106
107        self.enableGraphCombo(None)
108
109    def closeEvent(self, event):
110        """
111        Overwrite the close event - no close!
112        """
113        event.ignore()
114
115    def displayHelp(self):
116        """
117        Show the "Loading data" section of help
118        """
119        _TreeLocation = "html/user/sasgui/guiframe/data_explorer_help.html"
120        self._helpView.load(QtCore.QUrl(_TreeLocation))
121        self._helpView.show()
122
123    def enableGraphCombo(self, combo_text):
124        """
125        Enables/disables "Assign Plot" elements
126        """
127        self.cbgraph.setEnabled(len(PlotHelper.currentPlots()) > 0)
128        self.cmdAppend.setEnabled(len(PlotHelper.currentPlots()) > 0)
129
130    def loadFromURL(self, url):
131        """
132        Threaded file load
133        """
134        load_thread = threads.deferToThread(self.readData, url)
135        load_thread.addCallback(self.loadComplete)
136
137    def loadFile(self, event=None):
138        """
139        Called when the "Load" button pressed.
140        Opens the Qt "Open File..." dialog
141        """
142        path_str = self.chooseFiles()
143        if not path_str:
144            return
145        self.loadFromURL(path_str)
146
147    def loadFolder(self, event=None):
148        """
149        Called when the "File/Load Folder" menu item chosen.
150        Opens the Qt "Open Folder..." dialog
151        """
152        folder = QtGui.QFileDialog.getExistingDirectory(self, "Choose a directory", "",
153              QtGui.QFileDialog.ShowDirsOnly | QtGui.QFileDialog.DontUseNativeDialog)
154        if folder is None:
155            return
156
157        folder = str(folder)
158
159        if not os.path.isdir(folder):
160            return
161
162        # get content of dir into a list
163        path_str = [os.path.join(os.path.abspath(folder), filename)
164                    for filename in os.listdir(folder)]
165
166        self.loadFromURL(path_str)
167
168    def loadProject(self):
169        """
170        Called when the "Open Project" menu item chosen.
171        """
172        kwargs = {
173            'parent'    : self,
174            'caption'   : 'Open Project',
175            'filter'    : 'Project (*.json);;All files (*.*)',
176            'options'   : QtGui.QFileDialog.DontUseNativeDialog
177        }
178        filename = str(QtGui.QFileDialog.getOpenFileName(**kwargs))
179        if filename:
180            load_thread = threads.deferToThread(self.readProject, filename)
181            load_thread.addCallback(self.readProjectComplete)
182
183    def readProject(self, filename):
184        self.communicator.statusBarUpdateSignal.emit("Loading Project... %s" % os.path.basename(filename))
185        try:
186            manager = DataManager()
187            with open(filename, 'r') as infile:
188                manager.load_from_readable(infile)
189
190            self.communicator.statusBarUpdateSignal.emit("Loaded Project: %s" % os.path.basename(filename))
191            return manager
192
193        except:
194            self.communicator.statusBarUpdateSignal.emit("Failed: %s" % os.path.basename(filename))
195            raise
196
197    def readProjectComplete(self, manager):
198        self.model.clear()
199
200        self.manager.assign(manager)
201        for id, item in self.manager.get_all_data().iteritems():
202            self.updateModel(item.data, item.path)
203
204        self.model.reset()
205
206    def saveProject(self):
207        """
208        Called when the "Save Project" menu item chosen.
209        """
210        kwargs = {
211            'parent'    : self,
212            'caption'   : 'Save Project',
213            'filter'    : 'Project (*.json)',
214            'options'   : QtGui.QFileDialog.DontUseNativeDialog
215        }
216        filename = str(QtGui.QFileDialog.getSaveFileName(**kwargs))
217        if filename:
218            self.communicator.statusBarUpdateSignal.emit("Saving Project... %s\n" % os.path.basename(filename))
219            with open(filename, 'w') as outfile:
220                self.manager.save_to_writable(outfile)
221
222    def deleteFile(self, event):
223        """
224        Delete selected rows from the model
225        """
226        # Assure this is indeed wanted
227        delete_msg = "This operation will delete the checked data sets and all the dependents." +\
228                     "\nDo you want to continue?"
229        reply = QtGui.QMessageBox.question(self,
230                                           'Warning',
231                                           delete_msg,
232                                           QtGui.QMessageBox.Yes,
233                                           QtGui.QMessageBox.No)
234
235        if reply == QtGui.QMessageBox.No:
236            return
237
238        # Figure out which rows are checked
239        ind = -1
240        # Use 'while' so the row count is forced at every iteration
241        while ind < self.model.rowCount():
242            ind += 1
243            item = self.model.item(ind)
244            if item and item.isCheckable() and item.checkState() == QtCore.Qt.Checked:
245                # Delete these rows from the model
246                self.model.removeRow(ind)
247                # Decrement index since we just deleted it
248                ind -= 1
249
250        # pass temporarily kept as a breakpoint anchor
251        pass
252
253    def deleteTheory(self, event):
254        """
255        Delete selected rows from the theory model
256        """
257        # Assure this is indeed wanted
258        delete_msg = "This operation will delete the checked data sets and all the dependents." +\
259                     "\nDo you want to continue?"
260        reply = QtGui.QMessageBox.question(self,
261                                           'Warning',
262                                           delete_msg,
263                                           QtGui.QMessageBox.Yes,
264                                           QtGui.QMessageBox.No)
265
266        if reply == QtGui.QMessageBox.No:
267            return
268
269        # Figure out which rows are checked
270        ind = -1
271        # Use 'while' so the row count is forced at every iteration
272        while ind < self.theory_model.rowCount():
273            ind += 1
274            item = self.theory_model.item(ind)
275            if item and item.isCheckable() and item.checkState() == QtCore.Qt.Checked:
276                # Delete these rows from the model
277                self.theory_model.removeRow(ind)
278                # Decrement index since we just deleted it
279                ind -= 1
280
281        # pass temporarily kept as a breakpoint anchor
282        pass
283
284    def sendData(self, event):
285        """
286        Send selected item data to the current perspective and set the relevant notifiers
287        """
288        # should this reside on GuiManager or here?
289        self._perspective = self.parent.perspective()
290
291        # Set the signal handlers
292        self.communicator.updateModelFromPerspectiveSignal.connect(self.updateModelFromPerspective)
293
294        # Figure out which rows are checked
295        selected_items = []
296        for index in range(self.model.rowCount()):
297            item = self.model.item(index)
298            if item.isCheckable() and item.checkState() == QtCore.Qt.Checked:
299                selected_items.append(item)
300
301        if len(selected_items) < 1:
302            return
303
304        # Which perspective has been selected?
305        if len(selected_items) > 1 and not self._perspective.allowBatch():
306            msg = self._perspective.title() + " does not allow multiple data."
307            msgbox = QtGui.QMessageBox()
308            msgbox.setIcon(QtGui.QMessageBox.Critical)
309            msgbox.setText(msg)
310            msgbox.setStandardButtons(QtGui.QMessageBox.Ok)
311            retval = msgbox.exec_()
312            return
313
314        # TODO
315        # New plot or appended?
316
317        # Notify the GuiManager about the send request
318        self._perspective.setData(data_item=selected_items)
319
320    def freezeTheory(self, event):
321        """
322        Freeze selected theory rows.
323
324        "Freezing" means taking the plottable data from the Theory item
325        and copying it to a separate top-level item in Data.
326        """
327        # Figure out which rows are checked
328        # Use 'while' so the row count is forced at every iteration
329        outer_index = -1
330        theories_copied = 0
331        while outer_index < self.theory_model.rowCount():
332            outer_index += 1
333            outer_item = self.theory_model.item(outer_index)
334            if not outer_item:
335                continue
336            if outer_item.isCheckable() and \
337                   outer_item.checkState() == QtCore.Qt.Checked:
338                theories_copied += 1
339                new_item = self.recursivelyCloneItem(outer_item)
340                # Append a "unique" descriptor to the name
341                time_bit = str(time.time())[7:-1].replace('.', '')
342                new_name = new_item.text() + '_@' + time_bit
343                new_item.setText(new_name)
344                self.model.appendRow(new_item)
345            self.model.reset()
346
347        freeze_msg = ""
348        if theories_copied == 0:
349            return
350        elif theories_copied == 1:
351            freeze_msg = "1 theory copied from the Theory tab as a data set"
352        elif theories_copied > 1:
353            freeze_msg = "%i theories copied from the Theory tab as data sets" % theories_copied
354        else:
355            freeze_msg = "Unexpected number of theories copied: %i" % theories_copied
356            raise AttributeError, freeze_msg
357        self.communicator.statusBarUpdateSignal.emit(freeze_msg)
358        # Actively switch tabs
359        self.setCurrentIndex(1)
360
361    def recursivelyCloneItem(self, item):
362        """
363        Clone QStandardItem() object
364        """
365        new_item = item.clone()
366        # clone doesn't do deepcopy :(
367        for child_index in xrange(item.rowCount()):
368            child_item = self.recursivelyCloneItem(item.child(child_index))
369            new_item.setChild(child_index, child_item)
370        return new_item
371
372    def updateGraphCombo(self, graph_list):
373        """
374        Modify Graph combo box on graph add/delete
375        """
376        orig_text = self.cbgraph.currentText()
377        self.cbgraph.clear()
378        graph_titles = []
379        for graph in graph_list:
380            graph_titles.append("Graph"+str(graph))
381        self.cbgraph.insertItems(0, graph_titles)
382        ind = self.cbgraph.findText(orig_text)
383        if ind > 0:
384            self.cbgraph.setCurrentIndex(ind)
385        pass
386
387    def newPlot(self):
388        """
389        Create a new matplotlib chart from selected data
390
391        TODO: Add 2D-functionality
392        """
393        plots = GuiUtils.plotsFromCheckedItems(self.model)
394
395        # Call show on requested plots
396        for plot_set in plots:
397            new_plot = None
398            if isinstance(plot_set, Data1D):
399                new_plot = Plotter(self)
400            elif isinstance(plot_set, Data2D):
401                new_plot = Plotter2D(self)
402            else:
403                msg = "Incorrect data type passed to Plotting"
404                raise AttributeError, msg
405
406            new_plot.data(plot_set)
407            new_plot.plot()
408
409            # Update the global plot counter
410            title = "Graph"+str(PlotHelper.idOfPlot(new_plot))
411            new_plot.setWindowTitle(title)
412
413            # Add the plot to the workspace
414            self.parent.workspace().addWindow(new_plot)
415
416            # Show the plot
417            new_plot.show()
418
419            # Update the active chart list
420            self.active_plots.append(title)
421
422    def appendPlot(self):
423        """
424        Add data set(s) to the existing matplotlib chart
425
426        TODO: Add 2D-functionality
427        """
428        # new plot data
429        new_plots = GuiUtils.plotsFromCheckedItems(self.model)
430
431        # old plot data
432        plot_id = self.cbgraph.currentText()
433        plot_id = int(plot_id[5:])
434
435        assert plot_id in PlotHelper.currentPlots(), "No such plot: Graph%s"%str(plot_id)
436
437        old_plot = PlotHelper.plotById(plot_id)
438
439        # Add new data to the old plot
440        for plot_set in new_plots:
441            old_plot.data(plot_set)
442            old_plot.plot()
443
444    def chooseFiles(self):
445        """
446        Shows the Open file dialog and returns the chosen path(s)
447        """
448        # List of known extensions
449        wlist = self.getWlist()
450
451        # Location is automatically saved - no need to keep track of the last dir
452        # But only with Qt built-in dialog (non-platform native)
453        paths = QtGui.QFileDialog.getOpenFileNames(self, "Choose a file", "",
454                wlist, None, QtGui.QFileDialog.DontUseNativeDialog)
455        if paths is None:
456            return
457
458        if isinstance(paths, QtCore.QStringList):
459            paths = [str(f) for f in paths]
460
461        if not isinstance(paths, list):
462            paths = [paths]
463
464        return paths
465
466    def readData(self, path):
467        """
468        verbatim copy-paste from
469           sasgui.guiframe.local_perspectives.data_loader.data_loader.py
470        slightly modified for clarity
471        """
472        message = ""
473        log_msg = ''
474        output = {}
475        any_error = False
476        data_error = False
477        error_message = ""
478
479        number_of_files = len(path)
480        self.communicator.progressBarUpdateSignal.emit(0.0)
481
482        for index, p_file in enumerate(path):
483            basename = os.path.basename(p_file)
484            _, extension = os.path.splitext(basename)
485            if extension.lower() in GuiUtils.EXTENSIONS:
486                any_error = True
487                log_msg = "Data Loader cannot "
488                log_msg += "load: %s\n" % str(p_file)
489                log_msg += """Please try to open that file from "open project" """
490                log_msg += """or "open analysis" menu\n"""
491                error_message = log_msg + "\n"
492                logging.info(log_msg)
493                continue
494
495            try:
496                message = "Loading Data... " + str(basename) + "\n"
497
498                # change this to signal notification in GuiManager
499                self.communicator.statusBarUpdateSignal.emit(message)
500
501                output_objects = self.loader.load(p_file)
502
503                # Some loaders return a list and some just a single Data1D object.
504                # Standardize.
505                if not isinstance(output_objects, list):
506                    output_objects = [output_objects]
507
508                for item in output_objects:
509                    # cast sascalc.dataloader.data_info.Data1D into
510                    # sasgui.guiframe.dataFitting.Data1D
511                    # TODO : Fix it
512                    new_data = self.manager.create_gui_data(item, p_file)
513                    output[new_data.id] = new_data
514
515                    # Model update should be protected
516                    self.mutex.lock()
517                    self.updateModel(new_data, p_file)
518                    self.model.reset()
519                    QtGui.qApp.processEvents()
520                    self.mutex.unlock()
521
522                    if hasattr(item, 'errors'):
523                        for error_data in item.errors:
524                            data_error = True
525                            message += "\tError: {0}\n".format(error_data)
526                    else:
527
528                        logging.error("Loader returned an invalid object:\n %s" % str(item))
529                        data_error = True
530
531            except Exception as ex:
532                logging.error(sys.exc_value)
533
534                any_error = True
535            if any_error or error_message != "":
536                if error_message == "":
537                    error = "Error: " + str(sys.exc_info()[1]) + "\n"
538                    error += "while loading Data: \n%s\n" % str(basename)
539                    error_message += "The data file you selected could not be loaded.\n"
540                    error_message += "Make sure the content of your file"
541                    error_message += " is properly formatted.\n\n"
542                    error_message += "When contacting the SasView team, mention the"
543                    error_message += " following:\n%s" % str(error)
544                elif data_error:
545                    base_message = "Errors occurred while loading "
546                    base_message += "{0}\n".format(basename)
547                    base_message += "The data file loaded but with errors.\n"
548                    error_message = base_message + error_message
549                else:
550                    error_message += "%s\n" % str(p_file)
551
552            current_percentage = int(100.0* index/number_of_files)
553            self.communicator.progressBarUpdateSignal.emit(current_percentage)
554
555        if any_error or error_message:
556            logging.error(error_message)
557            status_bar_message = "Errors occurred while loading %s" % format(basename)
558            self.communicator.statusBarUpdateSignal.emit(status_bar_message)
559
560        else:
561            message = "Loading Data Complete! "
562        message += log_msg
563        # Notify the progress bar that the updates are over.
564        self.communicator.progressBarUpdateSignal.emit(-1)
565
566        return output, message
567
568    def getWlist(self):
569        """
570        Wildcards of files we know the format of.
571        """
572        # Display the Qt Load File module
573        cards = self.loader.get_wildcards()
574
575        # get rid of the wx remnant in wildcards
576        # TODO: modify sasview loader get_wildcards method, after merge,
577        # so this kludge can be avoided
578        new_cards = []
579        for item in cards:
580            new_cards.append(item[:item.find("|")])
581        wlist = ';;'.join(new_cards)
582
583        return wlist
584
585    def selectData(self, index):
586        """
587        Callback method for modifying the TreeView on Selection Options change
588        """
589        if not isinstance(index, int):
590            msg = "Incorrect type passed to DataExplorer.selectData()"
591            raise AttributeError, msg
592
593        # Respond appropriately
594        if index == 0:
595            # Select All
596            for index in range(self.model.rowCount()):
597                item = self.model.item(index)
598                if item.isCheckable() and item.checkState() == QtCore.Qt.Unchecked:
599                    item.setCheckState(QtCore.Qt.Checked)
600        elif index == 1:
601            # De-select All
602            for index in range(self.model.rowCount()):
603                item = self.model.item(index)
604                if item.isCheckable() and item.checkState() == QtCore.Qt.Checked:
605                    item.setCheckState(QtCore.Qt.Unchecked)
606
607        elif index == 2:
608            # Select All 1-D
609            for index in range(self.model.rowCount()):
610                item = self.model.item(index)
611                item.setCheckState(QtCore.Qt.Unchecked)
612
613                try:
614                    is1D = isinstance(item.child(0).data().toPyObject(), Data1D)
615                except AttributeError:
616                    msg = "Bad structure of the data model."
617                    raise RuntimeError, msg
618
619                if is1D:
620                    item.setCheckState(QtCore.Qt.Checked)
621
622        elif index == 3:
623            # Unselect All 1-D
624            for index in range(self.model.rowCount()):
625                item = self.model.item(index)
626
627                try:
628                    is1D = isinstance(item.child(0).data().toPyObject(), Data1D)
629                except AttributeError:
630                    msg = "Bad structure of the data model."
631                    raise RuntimeError, msg
632
633                if item.isCheckable() and item.checkState() == QtCore.Qt.Checked and is1D:
634                    item.setCheckState(QtCore.Qt.Unchecked)
635
636        elif index == 4:
637            # Select All 2-D
638            for index in range(self.model.rowCount()):
639                item = self.model.item(index)
640                item.setCheckState(QtCore.Qt.Unchecked)
641                try:
642                    is2D = isinstance(item.child(0).data().toPyObject(), Data2D)
643                except AttributeError:
644                    msg = "Bad structure of the data model."
645                    raise RuntimeError, msg
646
647                if is2D:
648                    item.setCheckState(QtCore.Qt.Checked)
649
650        elif index == 5:
651            # Unselect All 2-D
652            for index in range(self.model.rowCount()):
653                item = self.model.item(index)
654
655                try:
656                    is2D = isinstance(item.child(0).data().toPyObject(), Data2D)
657                except AttributeError:
658                    msg = "Bad structure of the data model."
659                    raise RuntimeError, msg
660
661                if item.isCheckable() and item.checkState() == QtCore.Qt.Checked and is2D:
662                    item.setCheckState(QtCore.Qt.Unchecked)
663
664        else:
665            msg = "Incorrect value in the Selection Option"
666            # Change this to a proper logging action
667            raise Exception, msg
668
669    def contextMenu(self):
670        """
671        Define actions and layout of the right click context menu
672        """
673        # Create a custom menu based on actions defined in the UI file
674        self.context_menu = QtGui.QMenu(self)
675        self.context_menu.addAction(self.actionDataInfo)
676        self.context_menu.addAction(self.actionSaveAs)
677        self.context_menu.addAction(self.actionQuickPlot)
678        self.context_menu.addSeparator()
679        self.context_menu.addAction(self.actionQuick3DPlot)
680        self.context_menu.addAction(self.actionEditMask)
681
682        # Define the callbacks
683        self.actionDataInfo.triggered.connect(self.showDataInfo)
684        self.actionSaveAs.triggered.connect(self.saveDataAs)
685        self.actionQuickPlot.triggered.connect(self.quickDataPlot)
686        self.actionQuick3DPlot.triggered.connect(self.quickData3DPlot)
687        self.actionEditMask.triggered.connect(self.showEditDataMask)
688
689    def onCustomContextMenu(self, position):
690        """
691        Show the right-click context menu in the data treeview
692        """
693        index = self.treeView.indexAt(position)
694        if index.isValid():
695            model_item = self.model.itemFromIndex(self.data_proxy.mapToSource(index))
696            # Find the mapped index
697            orig_index = model_item.isCheckable()
698            if orig_index:
699                # Check the data to enable/disable actions
700                is_2D = isinstance(model_item.child(0).data().toPyObject(), Data2D)
701                self.actionQuick3DPlot.setEnabled(is_2D)
702                self.actionEditMask.setEnabled(is_2D)
703                # Fire up the menu
704                self.context_menu.exec_(self.treeView.mapToGlobal(position))
705
706    def showDataInfo(self):
707        """
708        Show a simple read-only text edit with data information.
709        """
710        index = self.treeView.selectedIndexes()[0]
711        model_item = self.model.itemFromIndex(self.data_proxy.mapToSource(index))
712        data = model_item.child(0).data().toPyObject()
713        if isinstance(data, Data1D):
714            text_to_show = GuiUtils.retrieveData1d(data)
715            # Hardcoded sizes to enable full width rendering with default font
716            self.txt_widget.resize(420,600)
717        else:
718            text_to_show = GuiUtils.retrieveData2d(data)
719            # Hardcoded sizes to enable full width rendering with default font
720            self.txt_widget.resize(700,600)
721
722        self.txt_widget.setReadOnly(True)
723        self.txt_widget.setWindowFlags(QtCore.Qt.Window)
724        self.txt_widget.setWindowIcon(QtGui.QIcon(":/res/ball.ico"))
725        self.txt_widget.setWindowTitle("Data Info: %s" % data.filename)
726        self.txt_widget.insertPlainText(text_to_show)
727
728        self.txt_widget.show()
729        # Move the slider all the way up, if present
730        vertical_scroll_bar = self.txt_widget.verticalScrollBar()
731        vertical_scroll_bar.triggerAction(QtGui.QScrollBar.SliderToMinimum)
732
733    def saveDataAs(self):
734        """
735        Save the data points as either txt or xml
736        """
737        index = self.treeView.selectedIndexes()[0]
738        model_item = self.model.itemFromIndex(self.data_proxy.mapToSource(index))
739        data = model_item.child(0).data().toPyObject()
740        if isinstance(data, Data1D):
741            GuiUtils.saveData1D(data)
742        else:
743            GuiUtils.saveData2D(data)
744
745    def quickDataPlot(self):
746        """
747        Frozen plot - display an image of the plot
748        """
749        index = self.treeView.selectedIndexes()[0]
750        model_item = self.model.itemFromIndex(self.data_proxy.mapToSource(index))
751        data = model_item.child(0).data().toPyObject()
752
753        dimension = 1 if isinstance(data, Data1D) else 2
754
755        # TODO: Replace this with the proper MaskPlotPanel from plottools
756        new_plot = Plotter(self)
757        new_plot.data(data)
758        new_plot.plot(marker='o', linestyle='')
759
760        # Update the global plot counter
761        title = "Plot " + data.name
762        new_plot.setWindowTitle(title)
763
764        # Show the plot
765        new_plot.show()
766
767    def quickData3DPlot(self):
768        """
769        """
770        print "quickData3DPlot"
771        pass
772
773    def showEditDataMask(self):
774        """
775        """
776        print "showEditDataMask"
777        pass
778
779    def loadComplete(self, output):
780        """
781        Post message to status bar and update the data manager
782        """
783        assert isinstance(output, tuple)
784
785        # Reset the model so the view gets updated.
786        self.model.reset()
787        self.communicator.progressBarUpdateSignal.emit(-1)
788
789        output_data = output[0]
790        message = output[1]
791        # Notify the manager of the new data available
792        self.communicator.statusBarUpdateSignal.emit(message)
793        self.communicator.fileDataReceivedSignal.emit(output_data)
794        self.manager.add_data(data_list=output_data)
795
796    def updateModel(self, data, p_file):
797        """
798        Add data and Info fields to the model item
799        """
800        # Structure of the model
801        # checkbox + basename
802        #     |-------> Data.D object
803        #     |-------> Info
804        #                 |----> Title:
805        #                 |----> Run:
806        #                 |----> Type:
807        #                 |----> Path:
808        #                 |----> Process
809        #                          |-----> process[0].name
810        #     |-------> THEORIES
811
812        # Top-level item: checkbox with label
813        checkbox_item = QtGui.QStandardItem(True)
814        checkbox_item.setCheckable(True)
815        checkbox_item.setCheckState(QtCore.Qt.Checked)
816        checkbox_item.setText(os.path.basename(p_file))
817
818        # Add the actual Data1D/Data2D object
819        object_item = QtGui.QStandardItem()
820        object_item.setData(QtCore.QVariant(data))
821
822        checkbox_item.setChild(0, object_item)
823
824        # Add rows for display in the view
825        info_item = GuiUtils.infoFromData(data)
826
827        # Set info_item as the first child
828        checkbox_item.setChild(1, info_item)
829
830        # Caption for the theories
831        checkbox_item.setChild(2, QtGui.QStandardItem("THEORIES"))
832
833        # New row in the model
834        self.model.appendRow(checkbox_item)
835
836
837    def updateModelFromPerspective(self, model_item):
838        """
839        Receive an update model item from a perspective
840        Make sure it is valid and if so, replace it in the model
841        """
842        # Assert the correct type
843        if not isinstance(model_item, QtGui.QStandardItem):
844            msg = "Wrong data type returned from calculations."
845            raise AttributeError, msg
846
847        # TODO: Assert other properties
848
849        # Reset the view
850        self.model.reset()
851
852        # Pass acting as a debugger anchor
853        pass
854
855
856if __name__ == "__main__":
857    app = QtGui.QApplication([])
858    dlg = DataExplorerWindow()
859    dlg.show()
860    sys.exit(app.exec_())
Note: See TracBrowser for help on using the repository browser.