source: sasview/src/sas/qtgui/DataExplorer.py @ 469b4622

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

Minor perspective related work

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